Exceptions

Exceptions #

In Java exceptions occur during execution of a program. When an exception occurs normal flow of the program is disrupted and the program terminates abnormally. For that reason it is recommented that exceptions are handled.

Exceptions may occur for different reason. Some of these reasons are listed below:

  • User inputs wrong data
  • Interrupted connection
  • Buggy code

Some common exceptions are NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc.

Catching Exceptions #

In Java exceptions are catched with try and catch keywords. Below is an example on how try/catch works.

try {
	// Try block
} catch (Exception e) {
	// Catch block
}

Example Code #

try {
	Integer result = 1 / 0;
} catch (ArithmeticException e) {
	System.out.println(e.getMessage());
}

The example above will face an arithmetic exception within the try block. As a result the catch block run and print the exception message. If no exception is fired then catch block will not run at all.

Built-in Exceptions #

There are two types of built-in exception. They are checked exceptions and unchecked exceptions.

Checked Exceptions #

Checked exceptions are checked during compile time.

Unchecked Exceptions #

Unchecked exceptions occure during execution time.