Exception Handling in Java

Sri Kathiravan
7 min readSep 4, 2021

--

I’m just trying to share my thoughts and understanding of the exception handling. I took all this content from Wikipedia, Stack Overflow, Geeks for Geeks and some other’s medium articles. Basically, I’m wrapping all this content in my own preferred order/format. I believe that this article will help you to get a basic idea of exception handling and which may be used to recall the concepts while preparing for interviews.

Exception

An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e at run time, that disrupts the normal flow of the program’s instructions.

Types of Exception

  • Checked Exception
  • Unchecked Exception
  • Error

Checked Exception

  • Checked at the compile-time — Must be handled or declared. Otherwise, it will cause a compile-time error. E.g. — IO Exception.
  • The classes that directly inherit the Throwable class except RuntimeException and Error.

Unchecked Exception

  • Not checked at the compiled time — Not necessary to handle or declare. They won’t cause any compile-time error. E.g. — Arithmetic Exception.
  • The classes that inherit the RuntimeException.

Error

  • Error is irrecoverable. Some examples of errors are OutOfMemoryError, VirtualMachineError, Assertion Error, Etc.

Default Exception Handling — How JVM handle an Exception?

Refer to the flow chart here.

Java program to demonstrate exception is thrown how the run time system searches the call stack to find an appropriate exception handler:

class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found within this method.
static int divideByZero(int a, int b){

// this statement will cause ArithmeticException(/ by zero)
int i = a/b;

return i;
}

// The runTime System searches the appropriate Exception handler
// in this method also but couldn't have found. So looking forward
// on the call stack.
static int computeDivision(int a, int b) {

int res =0;

try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}

// In this method found appropriate Exception handler.
// i.e. matching catch block.
public static void main(String args[]){

int a = 1;
int b = 0;

try
{
int i = computeDivision(a,b);

}

// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
}

Customized Exception Handling

Java exception handling is managed via five keywords:

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

Try

  • Used to specify a block where we should place an exception code.
  • It means we can’t use try block alone. The try block must be followed by either catch or finally.

Catch

  • Used to handle the exception.
  • It must be preceded by try block which means we can’t use catch block alone.

Throw

  • Used to explicitly throw an exception from a method or any block of code.

throws

  • Used to declare exceptions.
  • Used in the signature of the method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
  • throws keyword is required only for checked exception and usage of throws keyword for the unchecked exception is meaningless.
  • throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of the program.
  • With the help of the throws keyword, we can provide information to the caller of the method about the exception.

Finally

  • It is executed whether an exception is handled or not.
  • The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection.

Important Examples

Understand the exact difference between these two examples.

EG — 1:

public static void main(String[] args) {  
try {
int data=50/0; //may throw exception
}
catch(ArithmeticException e) {
System.out.println(e);
}
System.out.println("rest of the code");
}

Output — 1:

java.lang.ArithmeticException: / by zero
rest of the code

EG — 2:

public static void main(String[] args) {  
try {
int data=50/0;
System.out.println("rest of the code");
}
catch(ArithmeticException e) {
System.out.println(e);
}
}

Output — 2

java.lang.ArithmeticException: / by zero

Nested try block

Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax

try {    
statement 1;
statement 2;

//try catch block within another try block
try {
statement 3;
statement 4;

//try catch block within another try block
try {
statement 5;
statement 6;
} catch(Exception e2) {
//exception message
}

} catch(Exception e1) {
//exception message
}

} catch(Exception e3) {
//exception message
}

Catch Multiple Exceptions

All catch blocks must be ordered from most specific to the most general. i.e. catch for ArithmeticException must come before catching for Exception.

User-defined Custom Exception in Java

Following steps are followed for the creation of user-defined Exception.

  • The user should create an exception class as a subclass of the Exception class. Since all the exceptions are subclasses of the Exception class, the user should also make his class a subclass of it. This is done as:
class MyException extends Exception
  • We can write a default constructor in his own exception class.
javaMyException(){}
  • We can also create a parameterized constructor with a string as a parameter. We can use this to store exception details. We can call the superclass (Exception) constructor from this and send the string there.
MyException(String str)
{
super(str);
}
  • To raise an exception of a user-defined type, we need to create an object to his exception class and throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;

Eg-1

class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}

Eg-2 — The constructor of the Exception class can also be called without a parameter and the call to super is not mandatory.

class MyException extends Exception
{

}

List of important built-in exceptions in Java

  • ArithmeticException — It is thrown when an exceptional condition has occurred in an arithmetic operation.
  • ArrayIndexOutOfBoundsException — It is thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
  • ClassNotFoundException — This Exception is raised when we try to access a class whose definition is not found
  • FileNotFoundException — This Exception is raised when a file is not accessible or does not open.
  • I Exception — It is thrown when an input-output operation failed or interrupted
  • Interrupted Exception — It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
  • NoSuchFieldException — It is thrown when a class does not contain the field (or variable) specified
  • NoSuchMethodException — It is thrown when accessing a method, which is not found.
  • NullPointerException — This exception is raised when referring to the members of a null object. Null represents nothing.
  • NumberFormatException — This exception is raised when a method could not convert a string into a numeric format.
  • RuntimeException - This represents an exception which occurs during runtime.
  • StringIndexOutOfBoundsException — It is thrown by String class methods to indicate that an index is either negative or greater than the size of the string.

Catching base and derived classes as exceptions

In Java, catching a base class exception before derived is not allowed by the compiler itself.

For example, following Java code fails in compilation with error message “exception Derived has already been caught”

class Base extends Exception {}
class Derived extends Base {}

public class Main {
public static void main(String args[]) {
try {
throw new Derived();
}
catch(Base b) {}
catch(Derived d) {}
}
}

Output:

error: exception Derived has already been caught
catch(Derived d) {}
^
1 error

Exception Propagation

An exception is first thrown from the top of the stack and if it is not caught, it drops down the call stack to the previous method. If not caught there, the exception again drops down to the previous method, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation.

Difference between final, finally and finalize

Refer here

Exception Handling with Method Overriding

There are two rules in method overriding.

  • If the superclass method does not declare an exception — If the superclass method does not declare an exception, the subclass overridden method cannot declare the checked exception but it can declare an unchecked exception.
  • If the superclass method declares an exception — If the superclass method declares an exception, the subclass overridden method can declare the same, subclass exception or no exception but cannot declare the parent exception.

Cases:

If the superclass method does not declare an exception:

  • Subclass overridden method declares checked exception — Compile time error.
  • Subclass overridden method declares unchecked exception — Valid.

If the superclass method declares an exception:

  • Subclass overridden method declares parent exception — Compile time error. i.e. parent class method declares ArithmeticException and the subclass method declares Exception.
  • Subclass overridden method declares same exception — Valid. i.e. parent class method and subclass method declares the same exception.
  • Subclass overridden method declares subclass exception — Valid. i.e. parent class method declares Exception and the subclass method declares ArithmeticException.
  • Subclass overridden method declares no exception — Valid.

Thanks…

I Am…..

I am a Software Engineer having experience in mobile app development with expertise in Java, Android and Flutter. Interested people can contact me through LinkedIn and Instagram.

--

--

Sri Kathiravan
Sri Kathiravan

Written by Sri Kathiravan

Software Developer | Java | Android | Flutter

No responses yet