|
Throwable is a built-in super class in Java which stands on the top most level of exception class hierarchy and all other are its sub classes. Below this we have Run time Exceptions which are basically defined automatically and have to be handled immediately as an when they arrive. e.g Division by zero.
Other type of Exception is termed as “Error”, the one which is not expected to arise during normal programming environment and are to be handled very diligently.
Let’s take each of the five ways in brief :
1. Try and Catch
Although, Java provides us with a default exception handler but it is always beneficial to handle these errors or exceptions manually as it facilitates in two ways, first we get to get the chance to fix the error on our own and second that it helps us to control and avoid the automatic termination of the program at any point of time.
It can be done by putting the segment of the code in the try block which has the possibility of having the error and them immediately putting the catch block next to try block with the type of exception to be handled along with a user friendly message or the treatment you want to give to that exception.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class TryCatchExample {
public static void main(String[] args) {
try {
// here we need to handle the scenario where file may not exist on the system.
// So what happens in that case. In such cases your program will stop abruptly.
// If you want that it should not stop abruptly then you need to handle that
// scenarion using try and catch block.
FileInputStream inputStream = new FileInputStream("this_file_does_not_exist.txt");
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
In the practical scenario, we can have multiple catches in one block of code and we can havr multiple catch clauses with respect to all exceptions. At the time of exception handling the catch clause which matches the type of exception will be executed first and rest all the catch clauses will be by passes hence non executed.
2. Throw
We get the exceptions not only from the Java run time environment but we do get the exceptions from our programs too with the help of Throw statement.
General syntax of throw is:
throw new Type of Exception
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ThrowExample {
public static void main(String[] args) throws Exception {
try {
FileInputStream inputStream = new FileInputStream("this_file_does_not_exist.txt");
}
catch (FileNotFoundException e) {
e.printStackTrace();
throw new Exception(e);
}
}
}
Throw object of superclass throwable or a sub class of it.
Whenever we get the throw statement in the program the execution is stopped immediately after this and the nearest possible try block is checked to find out if there is any catch statement that may match the type of exception which has come, if it doesn’t match , the control goes to another try and so on. Finally if any of the try doesn’t match the exception it is handled by the Default Java Exception handler and the program is halted at that place itself.
3. Throws
It becomes very important at the time of programming that if any exception is created by any method which that method cannot handle it has to be specifically intimated to the programmers so that they are aware of it before they call that method in their block of code and it is done with the help of Throws statement been written in that particular method itself.
All the exceptions which the method can throw without handling them should be displayed properly in the form of a list should be declared in the throws clause else it will lead to a compile time error.
General form of a method declaration that includes a throws clause is
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ThrowsExample {
public static void main(String[] args) throws Exception {
try {
FileInputStream inputStream = new FileInputStream("this_file_does_not_exist.txt");
}
catch (FileNotFoundException e) {
e.printStackTrace();
throw new Exception(e);
}
}
}
5. Finally
Whenever we get any type of exception in our code we try to handle that exception but in that process it happens that we always skip few lines of our code as the normal flow of the program gets disturbed and it may sometimes put us to serious situations. In order to handle this scenario we have one keyword called Finally which helps us to address this problem.
finally creates a block of code that will be executed after a try/catch block has
completed and before the code following the try/catch block. The finally block will
execute whether or not an exception is thrown. If an exception is thrown, the finally
block will execute even if no catch statement matches the exception. Any time a
method is about to return to the caller from inside a try/catch block, via an uncaught
exception or an explicit return statement, the finally clause is also executed just before the method returns. This can be useful for closing file handles and freeing up any other resources that might have been allocated at the beginning of a method with the intent of disposing of them before returning. The finally clause is optional. However, each try statement requires at least one catch or a finally clause
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FinallyExample {
public static void main(String[] args) throws Exception {
try {
FileInputStream inputStream = new FileInputStream("this_file_does_not_exist.txt");
}
catch (FileNotFoundException e) {
e.printStackTrace();
throw new Exception(e);
}
finally {
//finally will always be executed.
}
}
}
Java Built- in Exceptions
Java provides various built in classes to the programmer which facilitates coding in Java. The most common exceptions are subclasses of the standard type RuntimeException. They are not requirewd to be manually included in any method’s throws list.
They are basically defined as unchecked exceptions because they are not checked by the complier to see if a method handles or throws these exceptions.
A small list of these Unchecked Run Time Built in exceptions is mentioned below for your reference:
Exceptions Meaning
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric Format
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string
UnsupportedOperationException An unsupported operation was encountered
List of few Checked Exceptions available in Java are:
Exception Meaning
ClassNotFoundException Class not found.
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface.
IllegalAccessException Access to a class is denied.
InstantiationException Attempt to create an object of an abstract class or interface.
InterruptedException One thread has been interrupted by another thread.
NoSuchFieldException A requested field does not exist.
NoSuchMethodException A requested method does not exist.
|