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.

Java Exception Handling Hierarchy

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.

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.

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.

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.

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.

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.

Throw Keyword

Throw keyword is used for manually throwing java 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 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.

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

ExceptionDescription
ClassNotFoundExceptionClass not found
CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface
IllegalAccessExceptionAccess to a class is denied
InstantiationExceptionAttempt to create an object of an abstract class or interface
InterruptedExceptionOne thread has been interrupted by another thread
NoSuchFieldExceptionA requested field does not exist
NoSuchMethodException A requested method does not exist

List of unchecked exceptions

ExceptionDescription
ArithmeticExceptionArithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException Array index is out-of-bounds
ArrayStoreExceptionAssignment to an array element of an incompatible type
ClassCastExceptionInvalid cast
IllegalArgumentExceptionIllegal argument used to invoke a method
IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread
IllegalStateExceptionEnvironment or application is in incorrect state
IllegalThreadStateExceptionRequested operation not compatible with current thread state
IndexOutOfBoundsExceptionSome type of index is out-of-bounds
NegativeArraySizeException Array created with a negative size
NullPointerExceptionInvalid use of a null reference
NumberFormatExceptionInvalid conversion of a string to a numeric format
SecurityExceptionAttempt to violate security
StringIndexOutOfBoundsAttempt to index outside the bounds of a string
UnsupportedOperationExceptionAn 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