Java Exception Handling

Exceptions are used in Java Programming to handle errors and exceptional conditions.

This tutorial describes about exception and how to use them.

A program passes through the compile time and run time.

Exceptions are run time errors.

1) Compile time –Time during which the program is compiling.

2) Run time—Time during which the program is running.

 

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 occuring 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]

Problems with the default exception handling mechanism of Java

Default exception handlers of java don’t do the work properly they stop the program execution abruptly and give the weird output to the user. This is the reason why we should do the Exception handling by using our handlers. To handle we have to use try catch blocks. The lines of code that may throw some exception should be put in the try block and whatever we want our exception handlers to do should be put in to the catch block.

 

Here, by doing 1/0, our program will stop abruptly. And it will give a weird error message. Like,

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.

 

 

It will not stop program abruptly and give customize message like

 

 

Multiple catch blocks
There aremany subclasses of the main exception class. Depending upon the user’s input if different type of exception is occurring we need various type of catch block to handle them individually.

 

 

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 ArryIndexOutOfBoundExceptionis 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.

 

Making your own exception sub class
There are some situations that is not exception for java but it is exception for our project requirement. 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 itself.) so, this is the time when we manually create our own exception class. When we make this kind of exception it always extends the Exception class.
Throw keword
Throw keyword is used for manually throwing exception objects.

 

 

When a custom exception object is thrown it has to be handled through try and catch blocks because it cannot be handled by the fefault exception handler of java.

 

Throws
When we define 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. 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.
The difference between throw and throws:-
Throw is used to manually throw exception. If the definer don’t want to handle the exception using try and catch block than definer use throws keyword to indicate the caller that you must need to put try and catch block when you call the function. In this case definer delegates the work to the caller to put try and catch. So, if definer used more than 1 exceptions after throws keyword than caller is supposed to use corresponding catch block when function is being called.
All the custom exceptions are checked exception but there are also some inbuilt exception classes that are also checked.
List of checked exception

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 exception

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.

Comments

  1. Anonymous says:

    Great work! This is the kind of info that are supposed to be shared around the
    web. Thanks =)

  2. Seth Williams says:

    Very useful codes.

  3. 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.

  4. 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.

  5. canada goose ladies expedition parka says:

    Helpful blog, bookmarked the website with hopes to read more!

  6. 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.

  7. Seth Williams says:

    Thanks a lot Chinmay for your tutorial on exception handling. I found it very useful.

  8. 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.

Leave a Reply