Java – Exception Handling

In this java exception handling tutorial, we will learn, what is an exception, how to handle exception and important keywords and classes of exception handling in java with an example.

What is an Exception

Exception is an abnormal condition, which occurs at run time and terminates the flow of the program.

Just think about a situation where you have created a java program for division. In that example you have two numbers, first number will divided by second number. But at the run time user will divide first number by zero. As we know that division by zero is not possible, so it will generate an exception.

Java example to generate an exception.

class Demo
public static void main(String args[])
	int n=10;
//above line will generate an exception

Why an Exception is generated?

An exception can be generate for many reasons, some of them are:

  • When user input invalid (wrong type) data.
  • When we try to divide a number by zero.
  • If we want to open a file through code, which does not exist.
  • When we want to access an array index which does not exist.

How to Handle an Exception.

Handling of an exception is very important because of we can give a proper useful message to the user, when an exception is occur. Java has many classes and keywords to manage exceptions.

Java Exception Handling Keywords.

Java has some keywords to manage and generate an exception.

  • try – It is block in java, which includes the code which may generate an exception.
  • catch – It is used with the try block and executes only when an exception generates.
  • finally – It is also used with try and always executes whether an exception is generated or not.
  • throw – It is used to generate an exception forcefully.
  • throws – It indicates that what type of exception may be thrown by a method.

Java Exception Handling Classes

In Java, exceptions are generated as an object of exception class. All the classes are sub class of Exception class and Exception is a sub class of Throwable class. Some important exception classes are listed below.

  • ArithmeticException – This type of exception is thrown when an exceptional mathematical condition occurs.
  • FileNotFoundException – It thrown, when a code fails to open a file.
  • ArrayIndexOutOfBoundsException – It thrown, when a code try to access an array element with an illegal index.
  • NumberFormatException – It thrown, when we try to convert an appropriate format of a string to a number type.
  • IOException – It generates when a code fail to read or write a file.
  • SQLException – SQLException occurs when code is unable to communicate with the database.