You are on page 1of 5

Exception Handling in Java

What are Exceptions?

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Exceptions in Java

When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception.

Hierarchy of Exception Objects in Java

Types of Exception

Checked

All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses. If a methods throws a checked exception it needs to declare it using the throw keyword in method declaration. If not handled these will give compilation error. These are extending from RuntimeException class. If not handled these will not give compilation errors. These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.

Unchecked

Errors

Exception Propagation

Exceptions are handled using try, catch construct provided by Java Language When a methods throws an Exception the exceptions keeps on propagating as shown until an appropriate catch handler is found

Its a story of 5 words


Try Wrap code which can throw exception in a try block Catch If code in try block throws Exception then controls goes to appropriate catch block Finally This block comes after try or after catch block and executes irrespective of whether an Exception was thrown or not Throw Used to throw an exception from a method in case of an exceptional condition Throws Used in methods declaration to indicate which exceptions this methods can throw

Code Snippets

Watch out for the rectangles highlighting the exception handling keywords in action

Throwing Exceptions

The above snipped shows a method throwing an exception, note that it does not need to declare the exception in its method definition as IllegalArgumentException is RuntimeException.

Practical and Discussion

You might also like