Exception Handling in Java – Try, Catch & Finally

Exception handling is one of the most important mechanisms that are used in Java to manage the runtime errors. It helps in maintaining the flow of the application to be normal. In this chapter, various subjects related to Java exceptions including its type and the dissimilarities between checked and unchecked exceptions will be dealt with.

What is an exception in Java?

The simple meaning of exception is an unusual situation. In Java, an exception is defined as an event that disturbs the usual flow of the program. It is an error that is thrown by the program during its run.

What is exception handling?

Exception handling is the mechanism that is used to manage errors during the runtime. It handles various runtime errors including IO, Remote, SQL, and ClassNotFound.

The benefit of exception handling

The main function of exception handling is to maintain the normal flow of the program. When an exception occurs in a program, it disturbs the normal flow of the program. So exception handling is used to handle such errors. It executes all the statements in which there is no error and skips the statement in which there is an exception.

Hierarchy of Java exception classes

The root class of Java exception hierarchy is the java.lang.Throwable class. It is further inherited by Exception and Error subclasses. The following is a hierarchy of Java exception classes:

Hierarchy of Java exception classes

Types of Java Exceptions

There are two types of exceptions that mainly occur and they are:

  • Checked exception
  • Unchecked exception

However, Oracle has added another type of exception which is:

  • Error
  1. Checked exception

Checked exceptions are those exceptions that inherit Throwable class directly and are checked during compile-time. IOException and SQLException are a few examples of checked exceptions and it does not include RuntimeException and Error.

  1. Unchecked exception

ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException are the unchecked exceptions that are checked during runtime, not during the compile-time. Such exceptions inherit RuntimeException.

  1. Error

VirtualMachineError, OutOfMemoryError, and AssertionError are the errors that cannot be covered.

Java Exception Keywords

These are the keywords that are used in Java to handle exceptions:

Exception Handling: Try-Catch, Finally, throw & throws

1. try

The function of the try keyword is to specify the block in which the exception code is to be placed. It cannot be used alone and must be followed by either the catch keyword or the finally keyword.

2. catch

The catch keyword is used after the try keyword and the finally block can be used after it. So it cannot be used alone in handling exceptions.

3. finally

The finally keyword is used after the try and the catch keyword to execute if an exception has been handled or not. It executes the main code of the program.

A simple example of using try, catch and finally keyword

4. throw

The main function of the throw keyword is to throw an exception.

Example:

5. throws

The throws keyword is used with the method signature in order to declare exceptions. Like the throw keyword, the throws keyword does not throw an exception but it specifies that there might be a presence of exceptions in the method.

Example:

Common scenarios of Java exceptions

The following are the scenarios in which unchecked exceptions may occur:

  1. A scenario in which ArithmeticException occurs

The NullPointerException occurs if any number is divided by zero.

  1. A scenario in which NullPointerException occurs

The NullPointerException occurs while performing an operation on a variable if there is a null value in the variable.

  1. A scenario in which NumberFormatException occurs

The NumberFormatException occurs if the programmer wrongly formats a value.

  1. A scenario in which ArrayIndexOutOfBoundsException occurs

The ArrayIndexOutOfBoundsException occurs if the programmer inserts a value in the wrong index.

Internal working of Java try-catch block

The JVM checks if the exception has been managed or not. In the case in which the exception has been handled, then the rest of the code gets executed. However, in the opposite case, the JVM supplies a default exception handler that carries out the following functions:

  • In the first step, the exception description is printed out.
  • In the second step, the stack trace is printed out.
  • In the final step, the program gets terminated.

Java Catch multiple exceptions

Java multi-catch block

In Java, a multi-catch block is used when the programmer has to carry out various tasks at the occurrence of several exceptions.

Java nested try block

In Java, a nested try block is a try block that exists inside another try block.

Why use nested try block?

The nested try block is used to handle an exception in the case in which one error might arise from one block and the rest of the block might cause other errors.

Java finally block

The finally block is used in Java to carry out important functions in a code including stream and closing connection. It cannot be used alone and is used after either a try block or a catch block. The finally block is used even if the exception is handled.

Why use finally block?

The function of the finally block is to execute cleanup code in the programs. It executes code such as closing connection and closing a file.

Java Throw exception

Java Throw keyword

The main function of the throw keyword in Java is to throw an exception explicitly. It throws both checked and unchecked exception and mainly throws custom exceptions that are defined by the programmer.

Java Exception propagation

An exception gets thrown from the top of the stack in the first place. If it does not get caught, it then drops down the call stack to the previous method. If not caught in this step, the exception drops down to the previous method again. This goes on until the exception gets caught or reaches the bottom of the call stack. This whole process is called exception propagation.

Java throws keyword

The throws keyword is used in Java to handle the checked exceptions. It is used to declare the checked exceptions but it cannot declare unchecked exceptions or the errors. This is because the unchecked exceptions and the errors are the programmers’ own fault and they should be checked by the programmer themselves before using the code.

The throws keyword provides information to the programmer that an exception might occur in the program and gives suggestion to them to provide the exception handling code in order to ensure the normal flow of the program.

Which exceptions can be declared?

Only the checked exception can be declared by using the throws keyword. This is because unchecked exceptions like NullPointerException are under the control of the programmer so they can themselves correct the code. And errors like VirtualMachineError and StackOverflowError are beyond the control of the programmer so they cannot do anything if these errors occur.

The advantage of throws keyword in Java

The main advantage of the throws keyword in Java is that it provides information about the exception to the programmer.

Dissimilarities between throw and throws keyword in Java

There are various dissimilarities between the throw and throws keyword in Java. Some of them are mentioned below:

  • The main function of the throw keyword is to throw an exception explicitly. On the other hand, the main function of the throws keyword is to declare an exception.
  • By using the throw keyword, the checked exception cannot be propagated. But the checked exception can be propagated by using the throws keyword.
  • The throw keyword is followed by an instance but a class follows the throws keyword.
  • The throw keyword functions inside a method but the throws keyword functions inside a method signature.
  • The programmer cannot throw multiple exceptions using the throw keyword. However, the throws keyword can declare multiple exceptions.

Dissimilarities between final, finally, and finalize

Some of the dissimilarities between final, finally, and finalize are explained below:

  • The main function of the final keyword is to restrict class, variable, and method. It restricts the class from being inherited, the variable from being changed, and the method from being overridden. The main function of finally block is to execute codes whether the exception is managed or not. And the main function of the finalize method is to carry out clean up processing just before an object gets garbage collected.
  • Final is a keyword, finally is a block, and finalize is a method.

Exception handling in Java with method overriding

The rules to be followed while handling an exception with method overriding are as follows:

  • In the case in which an exception is not declared by the superclass method:

In the case in which an exception is not declared by the superclass method, the checked exception cannot be declared by the subclass overridden method but the unchecked exception can be declared by it.

  • In the case in which an exception is declared by the superclass method:

In the case in which an exception is declared by the superclass method, subclass exception and same exception can be declared by the subclass overridden method. It can also declare no exception at all but the parent exception cannot be declared by it.

Java custom exception

A custom exception is defined in Java as an exception that is created by the programmer themselves. It is also known as a user-defined exception and is it customizes the exception as per the need of the programmer. This way, the programmer can have their own exception and message by using the custom exception.

Leave a Reply

Your email address will not be published. Required fields are marked *