Java Exceptions Tutorial

Exception are used in Java to handle errors or any other exceptional event that occurs in the normal flow of program. There are several way Exception can occur in Java.

An exception can occur for many different reasons, including the following:

  • Data providing is not in expected format.

  • A user has entered invalid data.

  • A file based exceptions.

  • database related exceptions.

  • Network related exceptions.

Mainly the exception are caused by the User , or by the Programmer error or by the physical structure exception or all of the above.

categories of exceptions:

To understand how exception handling works in Java, you need to understand the three categories of exceptions.

  1. Checked Exception

  2. Runtime Exception

  3. Error

Checked Exception:

The User error is known as Checked Exception.

Example:

 For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation.

Runtime Exception:

The Runtime Exception is only occur in Program compilation time. Runtime Exception is an Unchecked Exception. These usually indicate programming bugs, such as logic errors or improper use of an API.

Error:

The second kind of exception is known as the error. When an exception occurs the JVM will create an exception object. These objects all derive from the Throwable class. The Throwable class has two main subclasses – Error and Exception. The Error class denotes an exception that an application is not likely to be able to deal with.

These exceptions are considered rare. For example, the JVM might run out of resources due to the hardware not being able to cope with all the processes it is having to deal with. It’s possible for the application to catch the error to notify the user but typically the application is going to have to close until the underlying problem is dealt with.
Exception Hierarchy:

In Java, exception can be checked or unchecked. They both fit into a class hierarchy. The following diagram shows Java Exception classes hierarchy.

  java-exceptions

 

Exception classes are sub-types of the Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class.

Errors are generated to indicate errors generated by the Java runtime environment. Example : JVM is out of Memory.

Example of Java Exception:

 

Manikandan is Founder and author of codenread. Tech Blogger by Passion | Computer Science Engineer by Qualification