Friday, November 15, 2013

User defined Exception in java

In this post, we'll see how to defined custom exceptions in java. We'll also see an example of user defined exception that elaborate more detail or how it is helpful in giving user friendly message to the user.




Java has built-in support for exceptions. 
The Java language supports exception handling in the form of following keywords

  • throw
  • throws
  • try
  • catch
  • finally




In most situations or cases, it will be sufficient to throws exception that are already provided in the Java library. For example, if you’re checking for the validity of the arguments passed to a public function, and you find them to be null or out of expected range, you can throw an IllegalArgumentException. 
However, for most non-trivial applications, it will be necessary for you to develop your own exception classes (custom exceptions) to indicate exceptional conditions.

Basic Exception hierarchy 


The basic syntax of exception handling-related keywords


How do you define a custom exception?

There are two options: you can extend

  • Exception
  • RuntimeException

If you want to force the users of your custom exception to handle the exception, then you can extend your exception class from the Exception class, which will make your custom exception a checked exception.

If you want to give flexibility to the users of your custom exception, and leave it to the users of your exception to decide if they want to handle the exception or not, you can derive your exception from the RuntimeException class.

So it is a design choice that you make to choose the base class of your custom exception.

How about extending the Throwable or Error class for custom exceptions?

  • The Throwable class is too generic to make it the base class of your exception, so it is not recommended.
  • The Error class is reserved for fatal exceptions that the JVM can throw (such as StackOverflowError), so it is not advisable to make this the base class of your exception



For extending from a base class, you need to see what methods the base class provides.
In this case, you want to create a custom exception by extending the Exception or RuntimeException classes. Since the Exception class is the base class of the RuntimeException class, it is sufficient to know the members of the Exception class.


Member Short description
Exception() Default constructor of the Exception class with no additional
information on the exception.
Exception(String) Constructor that takes a detailed information string about the constructor as
an argument.
Exception(String, Throwable) In addition to a detailed information string as an argument, this exception
constructor takes the cause of the exception (which is another exception) as
an argument.
Exception(Throwable) Constructor that takes the cause of the exception as an argument
String getMessage() Returns the detailed message
Throwable getCause() Returns the cause of the exception
Throwable[] getSuppressed() Returns the list of suppressed exceptions as an array.
void printStackTrace() Prints the stack trace (i.e., the list of method calls with relevant line
numbers) to the console (standard error stream). If the cause of an
exception (which is another exception object) is available in the exception,then that information will also be printed. Further, if there are any suppressed exceptions, they are also printed.



For illustrating how to create your own exception classes,we'll create a custom exception InvalidUserInputException.

Sample Output
Type an integer on the console
asdsa
Wrapping exception and throwing
Exception is of type:InvalidUserInputException: Invalid integer value entered
Original caught exception is of type java.util.InputMismatchException


In this InvalidUserInputException class, you did not introduce any new fields but you can add any fields if necessary. This is also a simple custom exception where the constructors simply call the base class versions of the same constructor type.

In this code, we use InvalidUserInputException just like any other exception already defined in the Java library. You are catching the InvalidUserInputException thrown from the readIntFromConsole() method in the main() method.
Since the cause of InvalidUserInputException is InputMismatchException, this exception name is printed in the console as a fully qualified name, java.util.InputMismatchException. You can think of InputMismatchException causing InvalidUserInputException; these two exceptions are known as chained exceptions.


One point to remember is here that as we have extended RuntimeException we are giving flexibility to the users of your custom exception, and leave it to the users of your exception to decide if they want to handle the exception or no.

I want you to try to create the same exception class by extending Exception class and see how it differ from the above exception .


Unchecked Exceptions — The Controversy
Why java does recommend to specify or throw Unchecked exception?
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical one they can be very numerous. Having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions (although you can).
One case where it is common practice to throw a RuntimeException is when the user calls a method incorrectly. For example, a method can check if one of its arguments is incorrectly null. If an argument is null, the method might throw a NullPointerException, which is an unchecked exception.

Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception



If you know anyone who has started learning java, why not help them out! Just share this post with them. Thanks for studying today!...

3 comments:

  1. Nicely written. Might be very handy during the interview.

    ReplyDelete
  2. Hey Pradeep, Thanks a lot for sharing this guide on user defined exceptions and these can be very hard to understand at times. Your guide was very useful and easy to understand. We too have some advanced tutorials that your readers can refer to at http://www.fireboxtraining.com/java

    ReplyDelete
  3. perfect explanation about java programming .its very useful.thanks for your valuable information.best java institute in chennai | best java training in velachery

    ReplyDelete