x

Java – Exception Handling

PREV     NEXT

Use Try and Catch:

  • A try block contains the code which may possibly raise an exception. A programmer would know the possible cases of exceptions which can erupt while executing a code.
  • Example when file handling is performed, possible subclasses of IOExceptions can occur.
  • The code which can possibly raise an exception can be encapsulated under the try block.

Syntax:


try{

//statements which may give rise to an exception

}

catch(<ExceptionType> object)

{ //log the exception / throw / terminate the program / do something to handle

}

  • Multiple catch blocks can also be written to handle different type of exceptions in a different way.

Specify ’throws’ keyword in the method constructor ( i.e. while declaring or defining the method):

  • The ‘throws’ keyword helps the method to literally throw the exception to the running stack.
  • The exception would be thrown to the previous method which called the current method which threw the exception.
  • Thus the exception is bubbled up until it finds a handler function. If no such handler function is found, the program leaves it to the JVM for handling, caring  about nothing.
  • Checked exceptions are subjected to be handled either by try, catch block or by using throws clause.

Example:

We can also specify multiple exceptions in the same method.

Example:

‘finally’ block:

  • The statements inside the finally block is executed, regardless of the exception being caught. Finally block gets executed whenever a try block exits.
  • The necessary actions which are to be taken before terminating a program like closing all the files opened, ending the SQL connection, rolling back or committing the database has to be defined in the finally block.
  • In other words, the clean up code can be included inside the ‘finally’ block so that everything is completed in an orderly manner.

Example:

‘throw’ keyword (Difference between throws clause and the throw clause)

  • Like explained previously, throws keyword must be used immediately after the method constructor and it throws the exception to the previous methods from which it was called.
  • The exception is bubbled up into the running stack till it finds a handler function.
  • But throw keyword can be used anywhere in the program when a programmer want to throw an exception of any type.

Usage of throw keyword:

  • The ‘throw’ keyword can be used whenever an exception needs to be thrown explicitly. Sometimes, Checked exceptions could not be handled by the client but it has to be handled and the compiler would force it to be handled.
  • When the programmer knows that in rare conditions, such exceptions can occur and the client would not be able to handle it. So in such cases, one may throw a RunTimeException in the handler function (catch). Hence the exception raised is indirectly wrapped up as a runtime exception which is not subjected to be handled.
  • In order to test the robustness (how well the exceptions are handled) of the program, one can test it, by throwing an exception by using ‘throw’. It is to check whether the exception is being caught. It is just for testing purpose since in real time, it may be difficult to find the exact input which raises some exceptions.

Example 1:


 List of subclasses of RunTimeException, Error and Exception (Checked Exception)  found in Java:

Runtime Exceptions Description
ArithmeticException Thrown when an exceptional Arithmetic condition occur (Example: Divide by zero)
ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal index.
ArrayStoreException Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.
ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
EnumConstantNotPresentException Thrown when an application tries to access an enum constant by name and the enum type contains no constant with the specified name.
IllegalArgumentException Thrown to indicate that a method has been passed an illegal or inappropriate argument.
IllegalMonitorStateException Thrown to indicate that a thread has attempted to wait on an object’s monitor or to notify other threads waiting on an object’s monitor without owning the specified monitor.
IllegalStateException Signals that a method has been invoked at an illegal or inappropriate time.
IllegalThreadStateException Thrown to indicate that a thread is not in an appropriate state for the requested operation.
IndexOutOfBoundsException Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.
NegativeArraySizeException Thrown if an application tries to create an array with negative size.
NullPointerException Thrown when an application attempts to use null in a case where an object is required.
NumberFormatException Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
SecurityException Thrown by the security manager to indicate a security violation.
StringIndexOutOfBoundsException Thrown by String methods to indicate that an index is either negative or greater than the size of the string.
TypeNotPresentException Thrown when an application tries to access a type using a string representing the type’s name, but no definition for the type with the specified name can be found.
UnsupportedOperationException Thrown to indicate that the requested operation is not supported.

Checked Exception subclass:

Checked Exceptions Description
CharConversionException Base class for character conversion exceptions.
EOFException Signals that an end of file or end of stream has been reached unexpectedly during input.
FileNotFoundException Signals that an attempt to open the file denoted by a specified pathname has failed.
IOException Signals that an I/O exception of some sort has occurred.
UnsupportedEncodingException The Character Encoding is not supported.
ClassNotFoundException Thrown when an application tries to load in a class through its string name using: The forName method in class Class.
NoSuchMethodException Thrown when a particular method cannot be found.
NoSuchFieldException Thrown when a particular field cannot be found.

Error Subclass:

Errors Description
AssertionError Thrown to indicate that an assertion has failed.
ClassFormatError Thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.
IllegalAccessError Thrown if an application attempts to access or modify a field, or to call a method that it does not have access to.
InternalError Thrown to indicate some unexpected internal error has occurred in the Java Virtual Machine.
LinkageError Subclasses of LinkageError indicate that a class has some dependency on another class; however, the latter class has incompatibly changed after the compilation of the former class.
OutOfMemoryError Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.
StackOverflowError Thrown when a stack overflow occurs because an application recurses too deeply
UnknownError Thrown when an unknown but serious exception has occurred in the Java Virtual Machine.
VirtualMachineError Thrown to indicate that the Java Virtual Machine is broken or has run out of resources necessary for it to continue operating.

PREV     NEXT



Like it? Please Spread the word!