• August 29, 2014
  • Core Java
  • Comments Off on Exception handling in java

Exception handling in java

Exceptional handling:

Exception handling is a mechanism to handle runtime errors, so that normal flow of the program can be maintained.

Exception Hierarchy:

Throwable is the super class. 

exception classes

 

 Advantages/Benefits of exceptional handling:

  1. 1. Using exceptional handling we can separate the error handling code from normal code.
  2. 2. Using exceptional handling we can differentiate the error types.
  3. 3. Normal flow of program can be maintained.

Types of Exception:

  1. 1. Checked exception.
  2. 2. Unchecked exception.
  3. 3. Error.

Checked exceptions:

Checked exceptions are those exceptional conditions that are checked by compiler at the compile time. A checked exception forces you to either use try-catch or throws. All exceptions except Error, RuntimeException, and their subclasses are checked exceptions.

e.g. – IOException, SQLException etc.

Unchecked exceptions:

Unchecked exceptions are those exceptional conditions that are not checked by compiler at the compile time. Unchecked exceptions are checked at runtime. An unchecked exception not forces you to either use try-catch or throws. RuntimeException and their subclasses are unchecked exceptions. This Exception can be avoided by programmer.

e.g. – NullPointerException, ArithmeticException etc.

Error:

Errors are those exceptional conditions that are not checked by compiler at the compile time. Errors are checked at runtime. An error not forces you to either use try-catch or throws. Error and their subclasses are represents errors. Error can’t be avoided by programmer, it is irrecoverable.

e.g. – OutOfMemoryError etc.

How to write an exception handler?

To write a simple exception handler, first enclose the code that might throw an exception within try block. When an exception occurs in try block, it will be handled by an appropriate exception handler. Exception handler can associate with try block by using catch block or finally block after it.

Note: catch and finally block both can be attached with single try block. Hierarchy should be try-catch-finally.

To understand more, let us see the keywords used in exception handling.

  1. 1. try
  2. 2. catch
  3. 3. finally
  4. 4. throw
  5. 5. throws

 
Next Topic: try and catch blocks in java with example.
Previous Topic: Some important terms for Exception Handling.

Related Topics:

Some important terms for Exception Handling.
Exception handling in java.
try and catch blocks in java with example.
Multiple catch blocks in java with example.
Nested try block in java with example.
Finally in java with example.
throw in java with example.
throws in java with example.
Exception propagation in java with example.
Exception handling with method overriding in java.
Custom exception in java with example.
Commonly used exception methods of Throwable class in java.

 


Comments are closed.