What are Exceptions in Java?
An Exception in java is an object that describes an exceptional condition in the program. A java exception object may be either generated in the code manually or automatically by the java run time system.
Java Exception Hierarchy
All types of java exceptions are subclass of the inbuilt class Throwable. The two sub classes of Throwable are Exception and Error. The branch Exception deals with those exceptional conditions that the user program should handle. Exception further branches into RunTimeException and Checked Exceptions. RuntimeExceptions are those exceptions that are automatically defined for the programs that we write, like ArithmeticException, NullPointerException etc. The other branch is Error, which defines exceptions that are not expected to be handled by our program.
A java program passes through compile time and run time. Exceptions are run time errors.
Exception is an inbuilt class in the java.lang package. There are many sub classes of Exception class like ArithmeticException, NullpointerException etc.
Depending upon the nature of the problem occurring during run time, java creates the appropriate Exception object and throws it.
For example: int i = 1/0; [Java will throw ArithmeticException type of object]
Why do we need to do Java Exception handling?
Java’s Default exception handlers doesn’t do the work properly, they stop the program execution abruptly and gives a weird output to the user. This is the reason why we should do exception handling. To do java exception handling we have to use try and catch blocks. The lines of code that may throw some exception should be put in the try block and whatever we want to be done should be put in to the catch block.
1 2 3 4 5 6 7 8 | public class Exception_Demo { public static void main(String[] args) { int i = 1 / 0; System.out.println("After division by 0"); } } |
Here, by doing 1/0, our program will stop abruptly. And it will give a weird error message. Like,
1 2 | Exception in thread "main" java.lang.ArithmeticException: / by zero at Exception_Demo.main(Exception_Demo.java:6) |
But on using try and catch the problem is overcome.
Try Catch Block in Java Exception Handling
- Try Block– Those code that may lead to exceptions during run time are generally put inside the try block.
- Catch Block– What ever we want to do when ever any exception occurs should be put in the catch block.
1 2 3 4 5 6 7 8 9 10 11 12 | public class Try_Catch { public static void main(String[] args) { try { int i = 1 / 0; System.out.println("After division"); } catch (Exception e) { System.out.println("Division by 0"); e.printStackTrace(); } System.out.println("After try catch"); } } |
Due to the use of try catch block the above program will not stop abruptly, rather it will give a customized exception message during run time.
1 2 3 4 | Division by 0 java.lang.ArithmeticException: / by zero at Try_Catch.main(Try_Catch.java:8) After try catch |
Multiple catch blocks
There are many sub classes of the class Exception like ArithmeticException, NullPointerException etc. During run time different type of exception may occur depending on different conditions. So to handle the problems differently in different circumstances we need to have multiple catch blocks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | public class Multi_Catch { public static void main(String[] args) { try { int len = args.length; if (len == 0) { int i = 1 / 0; } if (len == 1) { int j[] = new int[3]; j[10] = 4343; } } catch (ArithmeticException e) { System.out.println("you have not " + "entered any argument"); } catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception } catch (Exception e) { // TODO: handle exception } } } |
In this example, if length is 0 than it will be caught by catch block handling ArithmeticException. If we go out of the range of the array an ArryIndexOutOfBoundException is thrown. Programs may have various type of exceptions which can be handled through multiple catch blocks. In this example third catch block is for general Exception type. The general Exception catch block should be put at the end.
How to Create Custom Exception Class?
There are some situations that is not an exception for java but it is an exception for our project. For example if you want to run your program only when user gives commandline input (this is your program need which is not an exception for java) so, this is the time when we manually create our own exception class. To create a custom exception we have to extent the inbuilt Exception class.
1 2 3 | public class No_Commandline_Exception extends Exception { } |
Throw Keyword
Throw keyword is used for manually throwing java exception objects.
1 2 3 4 5 6 7 8 9 10 11 12 13 | public class Throw_Demo { // throw keyword is used for manually throw exception object public static void main(String[] args) { No_Commandline_Exception obj = new No_Commandline_Exception(); try { throw obj; } catch (No_Commandline_Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } |
When a custom exception object is thrown it has to be handled through try and catch blocks because it cannot be handled by the default exception handler of java.
Throws Keyword
When we define a function and we don’t want to put try and catch block than we can use throws keyword. The caller of the function has to put the try and catch blocks. Throws keyword is for delegating the exception handling mechanism to the caller of the function.
eg.
1 | static void fun() throws No_Commandline_Exception,ArithmeticException |
Checked and unchecked exception
Unchecked exceptions are those exceptions that can be handling by java’s default exception handlers. If we try to throw unchecked exception inside a function we don’t need to put try and catch block nor the throws.
Checked exceptions are those exceptions that can’t handle by java’s default exception handlers.
When a checked exception is thrown from inside a function we are bound to put the try and catch block or the throws declaration.
List of checked exceptions
Exception | Description |
---|---|
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 |
List of unchecked exceptions
Exception | Description |
---|---|
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 |
Anonymous says
Great work! This is the kind of info that are supposed to be shared around the
web. Thanks =)
Seth Williams says
Very useful codes.
r4 nintendo ds says
I really appreciate the information you confirmed there. Keep carrying out what you are carrying out. Resources like the one particular you talked about is extremely helpful.
billiga woolrich jackor says
I like what you guys are usually up too. Suchh clever work and reporting!
Keep up the fantastic works guys I’ve included you
guys to our blogroll.
canada goose ladies expedition parka says
Helpful blog, bookmarked the website with hopes to read more!
maillot de football americain says
This website has a lot very good info on it, I check on it each time Ia??m on the internet. I wish other internet sites put in as a lot time as this one does making details clearer to visitors like myself. I advocate this website to all of my facebook pals. This internet site will make some huge passive earnings Ia??m sure.
Seth Williams says
Thanks a lot Chinmay for your tutorial on exception handling. I found it very useful.
canada goose site officiel says
Hello! Someone in my Facebook group shared this website with us
so I came to look it over. I’m definitely loving the information.
I’m book-marking and will be tweeting this to my followers!
Exceptional blog and superb stgyle and design.