User-Defined Exceptions

Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, user can also create exceptions which are called ҵser-defined ExceptionsҮ Following steps are followed for the creation of user-defined Exception.

  1. The user should create an exception class as a subclass of Exception class. Since all the exceptions are subclasses of Exception class, the user should also make his class a subclass of it. This is done as:


    \begin{lstlisting}
class MyException extends Exception
\end{lstlisting}

  2. We can write a default constructor in his own exception class.


    \begin{lstlisting}
MyException(){}
\end{lstlisting}

  3. We can also create a parameterized constructor with a string as a parameter. We can use this to store exception details. We can call super class(Exception) constructor from this and send the string there.


    \begin{lstlisting}
MyException(String str)
{
super(str);
}
\end{lstlisting}

  4. To raise exception of user-defined type, we need to create an object to his exception class and throw it using throw clause, as:


    \begin{lstlisting}
MyException me = new MyException(ԅxception detailsԩ;
throw me;
\end{lstlisting}

The following program illustrates how to create own exception class MyException. Details of account numbers, customer names, and balance amounts are taken in the form of three arrays. In main() method, the details are displayed using a for-loop. At this time, check is done if in any account the balance amount is less than the minimum balance amount to be ept in the account. If it is so, then MyException is raised and a message is displayed Balance amount is less.


\begin{lstlisting}
\par
// Java program to demonstrate user defined exception
\...
...\par
catch (MyException e) {
e.printStackTrace();
}
}
}
\end{lstlisting}

Runtime Error:


\begin{lstlisting}
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
\end{lstlisting}

Output:


\begin{lstlisting}
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
\end{lstlisting}