Java Documentation

1.6 Exception Handling

How Java handles runtime errors using exceptions, try-catch blocks, and the throw and throws keywords.

What is an Exception?

An exception is an unwanted or unexpected event that occurs at runtime and disrupts the normal flow of a program. Instead of crashing, Java represents such situations as objects so they can be caught and handled gracefully.

Categories of Exceptions

Java groups abnormal conditions into three main categories. Knowing the difference helps you decide what can be recovered from in code and what is outside your control.

Checked

Detected at compile time. The compiler forces you to handle or declare them (for example, IOException).

Unchecked

Occur at runtime and usually indicate programming mistakes (for instance, ArithmeticException orNullPointerException).

Error

Serious problems related to the JVM or system resources that applications normally cannot handle (for example,StackOverflowError).

try-catch Block

The basic building blocks of exception handling are the try and catch blocks. Risky code goes inside the try block, and the catch block defines how to respond if an exception occurs.

HandlingException.java
public class HandlingException {
    public static void main(String[] args) {
		int a = 0;
		int b = 0;

		try {
		    b = 10/a; // divide by zero : exception
		    System.out.println("Hey There, from try block");

		} catch (Exception e) {
		    System.out.println("Something went wrong, "+e);
            // exception will be handled here
		}

		System.out.println(" we got b = "+b);
		System.out.println("Bye there !");
	}
}
Reference & full codeView on GitHub

Without the catch block, this program would terminate with an arithmetic error. With proper handling, the program prints a friendly message and continues.

Output:

Something went wrong, java.lang.ArithmeticException: / by zero
 we got b = 0
Bye there !

try with Multiple catch Blocks

Sometimes a single statement may throw different kinds of exceptions. In that case, you can attach multiple catch blocks to one try block and handle each exception type separately.

  • Each catch block specifies a different exception class.
  • The first matching catch block (from top to bottom) is executed.
  • More specific exception types should be caught before general ones.
TryMultipleCatch.java
public class TryMultipleCatch
{
	public static void main(String[] args) {
		int a = 1;
		int b = 0;
        int num[] = {1, 2, 3, 4, 5};

		try {
		    b = 10/a; 
            System.err.println(num[7]);
		    System.out.println("Hey There, from try block");

		} 
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of stack, "+e);

        } catch (Exception e) {
		    System.out.println("Something went wrong, "+e);
		} 

		System.out.println(" we got b = "+b);
		System.out.println("Bye there !");
	}
}
Reference & full codeView on GitHub

Output:

Array index out of stack, java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
 we got b = 10
Bye there !

throw Keyword

The throw keyword is used inside a method to create and explicitly throw an exception object at a particular point in your code.

  • Usually used when you detect an invalid state or bad input.
  • Can throw built-in exceptions or your own custom exceptions.
Throw.java
public class Throw {
    public static void main(String[] args) {
        {
            int j=0;
            try {

                if(j==0) {
                    throw new ArithmeticException("Message Will be here");
                }
            } catch(ArithmeticException e) {
                j = 100;
                System.err.println("Cannot divide "+e);
            }
            System.err.println(j);
            System.err.println("Ends here");
        }
    }
}
Reference & full codeView on GitHub

Output:

Cannot divide java.lang.ArithmeticException: Message Will be here
100
Ends here

throws Keyword

The throws clause is written in a method signature to declare that the method might pass certain exceptions to its caller instead of handling them locally.

  • Used mainly with checked exceptions like IOException.
  • Forces callers either to catch the exception or declare it again.
Throws.java
/* it provides exception to be handled in call section */

class Calculate {
    public void division(int a, int b) throws ArithmeticException {
        int d = a/b;
        System.err.println("d = "+d);
    }
}

public class Throws {
    public static void main(String[] args) {
        Calculate calc = new Calculate();

        try {
            calc.division(0, 0);
        } catch (ArithmeticException e) {
            System.err.println("Divide by Zero is not possible");
        }
    }
}
Reference & full codeView on GitHub

Output:

Divide by Zero is not possible

Throw vs Throws

  • throw: used inside a method body to create and immediately throw an exception object.
  • throws: used in a method signature to declare that the method may throw certain checked exceptions to its caller.
  • Often used together: a method throws an exception type, and uses throw when the exceptional condition occurs.

The finally Block

The finally block contains code that should run whether an exception is thrown or not. It is commonly used for resource cleanup, such as closing files, network connections, or database sessions.

Even if a method returns early or an exception is thrown and caught, code inside finally still executes.
Finally.java
public class Finally {
	public static void main(String[] args) {
		int a = 1;
		int b = 0;
        int num[] = {1, 2, 3, 4, 5};

		try {
		    b = 10/a; 
            System.err.println(num[7]);
		    System.out.println("Hey There, from try block");

		} 
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of stack, "+e);

        } catch (Exception e) {
		    System.out.println("Something went wrong, "+e);
		} finally {
            System.out.println("This is finally block, I will execute always");
        }

		System.out.println(" we got b = "+b);
		System.out.println("Bye there !");
	}
}
Reference & full codeView on GitHub

Output:

Array index out of stack, java.lang.ArrayIndexOutOfBoundsException: Index 7 out of bounds for length 5
This is finally block, it will execute always
 we got b = 10
Bye there !

User Defined Exceptions

While Java provides many built-in exception classes, developers often need to customize exceptions according to specific user needs. These are known as User-Defined Exceptions.

How to Create Custom Exceptions

In Java, an exception is simply an object of an exception class. We can create our own Exception classes by extending the built-in Exception class:

  • By creating a class that extends the Exception class (the superclass of all exception classes).
UserDefinedException.java
class NCITexception extends Exception {
    public NCITexception(String str) {
        super(str);
    }
}

public class UserDefinedException {
    public static void main(String arr[]) {
        
        try {
            
            System.out.println("Here we will try to throw NCITexception");
                throw new NCITexception("NCIT Exception Occured -- Message");
                
        } catch (NCITexception e) {
            
            System.out.println("Exception: " + e);
            
        }
        
        System.out.println("End of the program");
        
    }
}
Reference & full codeView on GitHub

Output:

Here we will try to throw NCITexception
Exception: NCITexception: NCIT Exception Occured -- Message
End of the program