Curriculum
Course: Learn Java Programming
Login

Curriculum

Learn Java Programming

Video lesson

Exception Hierarchy, Checked, and Unchecked Exception in Java

In this lesson, you will learn

  • Exception Hierarchy
  • Checked and Unchecked Exceptions
  • Examples

 

Exception Hierarchy

The exception hierarchy in Java is rooted in the java.lang.Throwable class, which is divided into two main subclasses: Error and Exception.

This hierarchy is essential for understanding how exceptions are handled and how to create custom exceptions.

 

The Throwable Class

  1. It is the superclass of all errors and exceptions in Java.
  2. You can throw only those exception objects that are derived from the Throwable or its subclasses.

It has two subclasses

1. Exception:

  • The Exception class represents the conditions that a program should handle.
  • This class is the base class for all exception classes other than the unchecked exceptions (which are subclasses of RuntimeException).

2. Error:

  • The Error class defines the exceptions related to the Java run-time environment and is intended for errors from which recovery is not expected or possible.
  • For examples include OutOfMemoryError and StackOverflowError.
  • The JVM typically uses these to indicate serious problems that are not intended to be caught and handled by applications.

 

Understanding Checked vs. Unchecked Exceptions

 

Checked Exceptions:

Definition

  • Checked exceptions are exceptions that are checked at compile time, and the compiler forces you to handle them.
  • Checked exceptions must be either caught or declared in the method’s throws clause.
  • These exceptions are subclasses of the Exception class (excluding RuntimeException).
  • For example, IOException is a checked exception. If you’re reading a file from a disk, you must handle or declare IOException to deal with potential IO problems.

Characteristics:

  • Compile-time checking: The compiler verifies that you have either caught these exceptions using a try-catch block or declared them in the method’s throws clause.
  • Mandatory handling: If a method might throw a checked exception, the calling method must acknowledge and handle it.
  • External factors: They often arise from external factors like I/O operations, network connections, or database interactions.

Examples:

  • IOException: Thrown during input/output operations.
  • FileNotFoundException: Thrown when a file is not found.
  • SQLException: Thrown during database access.
  • ClassNotFoundException: Thrown when a class cannot be found.
  • InterruptedException: Thrown when a thread is interrupted.

 

Important Points!

It is mandatory for a programmer to handle the checked exceptions If not handled, then a compile-time error occurs.

The checked exceptions are the objects of the Exception class or any of its subclasses excluding the RuntimeException and Error class.

 

How to Handle Checked Exception?

There are two main methods to handle checked exceptions:

1. Using ‘throws’ Clause

  • The throws clause is used in a method’s declaration to indicate that the method may throw one or more exceptions.
  • This does not handle the exception within the method itself but rather passes the responsibility of handling the exception to the method that calls this method.

Syntax

public returnType methodName(parameters) throws ExceptionType1, 
      ExceptionType2 {
    // Code that might throw an exception
}

Consider the following example where the readLine() method is used to take input using the BufferedReader class.

 

Example: Check Even Number

package ch12.l5;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class CheckedExceptionExample1 {
	
	public static String isEven(int number) {
		return number%2==0?"Even":"Odd";
	}

	public static void main(String[] args) {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		System.out.println("Enter any number: ");
		int x = Integer.parseInt(br.readLine());
		System.out.println("x is "+isEven(x)+" number");
	}
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException

	at jcodebook
ch12.l5.CheckedExceptionExample1.main(CheckedExceptionExample1.java:16)

Explanation

The above program displays a compilation error because the readLine() method throws a checked exception i.e. IOException which must be handled explicitly in the program.

Here’s an example of declaring a method that might throw an IOException, which is a checked exception. The calling method is responsible for handling this exception.

 

Example: Handling Checked Exception using ‘throws’ Clause

package ch12.l5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CheckedExceptionExample1 {
	
	public static String isEven(int number) {
		return number%2==0?"Even":"Odd";
	}

	public static void main(String[] args) throws IOException {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		System.out.println("Enter any number: ");
		int x = Integer.parseInt(br.readLine());
		System.out.println(x+" is a "+isEven(x)+" number");
	}
}

Output

Test Case-1:
Enter any number: 
9
9 is a Odd number
Test Case-2:
Enter any number: 
12
12 is a Even number

 

2. Handling Checked Exception using ‘try-catch’ Clause

  • The try-catch block is used to catch and handle exceptions.
  • If an exception occurs within the try block, execution is transferred to the corresponding catch block where that exception type is specified.

Syntax

try {
    // Code that might throw an exception
} catch (ExceptionType name) {
    // Code to handle the exception
}

 

Example: Handling Checked Exception using ‘try-catch’ Clause

package ch12.l5;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CheckedExceptionExample2 {
	
	public static String isEven(int number) {
		return number%2==0?"Even":"Odd";
	}

	public static void main(String[] args) {
		InputStreamReader isr = new InputStreamReader(System.in);
		BufferedReader br = new BufferedReader(isr);
		System.out.println("Enter any number: ");
		int x=0;
		try {
			x = Integer.parseInt(br.readLine());
		} 
		catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println(x+" is a "+isEven(x)+" number");
	}
}

Output

Test Case-1:
Enter any number: 
9
9 is a Odd number
Test Case-2:
Enter any number: 
12
12 is a Even number

 

List of Checked Exceptions

Below is a summary table of some commonly encountered checked exceptions in Java with a brief description for each.

Exception Class Package Description
IOException java.io General class for I/O-related failures.
FileNotFoundException java.io Thrown when a file specified by a pathname does not exist.
SQLException java.sql Represents database access errors or other errors related to database operations.
ClassNotFoundException java.lang Thrown when an application tries to load a class by name and the class cannot be found.
ParseException java.text Thrown when parsing operations fail.
MalformedURLException java.net Thrown to indicate a malformed URL has occurred.
NoSuchMethodException java.lang Thrown when a requested method could not be found.
InterruptedException java.lang Thrown when a thread is interrupted while it is waiting, sleeping, or doing another operation.

 

Unchecked Exceptions

  • Unchecked exceptions are exceptions that are not checked by the compiler and the compiler does not force you to handle them.
  • These are exceptions that do not need to be declared or caught.
  • They are subclasses of the RuntimeException class.
  • For example, ArithmeticException is an unchecked exception that might occur when dividing a number by zero.

Characteristics:

  • No compile-time checking: The compiler does not verify if you have handled these exceptions.
  • Optional handling: You are not required to catch or declare them, although you can.
  • Programming errors: They often indicate bugs in your code, such as null pointer dereferences, array index out-of-bounds errors, or arithmetic errors.

Examples:

  • NullPointerException: Thrown when accessing a null object.
  • ArrayIndexOutOfBoundsException: Thrown when accessing an invalid array index.
  • ArithmeticException: Thrown during arithmetic errors (e.g., division by zero).
  • IllegalArgumentException: Thrown when a method receives an invalid argument.
  • ClassCastException: Thrown during invalid type casting.

 

     

    Example 1: Unchecked Exception: Handling ArithmeticException

    An ArithmeticException can occur during arithmetic operations, for example, when dividing by zero. Catching this exception can help handle mathematical errors gracefully.

    public class ArithmeticExceptionHandling {
        public static void main(String[] args) {
            try {
                int result = 10 / 0;
                System.out.println("Result: " + result);
            } catch (ArithmeticException e) {
                System.out.println("Caught ArithmeticException: 
                Cannot divide by zero.");
            }
        }
    }
    

    Output

    Caught ArithmeticException: Cannot divide by zero.
    
    

     

    Example 2: Unchecked Exception: Handling NullPointerException

    A NullPointerException occurs when an application attempts to use null in a case where an object is required. Catching this exception can prevent the application from crashing when accessing null references.

    public class NullPointerExceptionHandling {
        public static void main(String[] args) {
            String text = null;
            try {
                System.out.println(text.length());
            } catch (NullPointerException e) {
                System.out.println(e);
            }
        }
    }
    

    Output

    java.lang.NullPointerException: Cannot invoke "String.length()" because "text" is null
    
    

     

    List of Unchecked Exceptions

    Below is a summary table of some commonly encountered unchecked exceptions in Java. These exceptions are inherited from java.lang.RuntimeException and are not required to be caught or declared thrown by a method.

    Exception Class Description
    NullPointerException Thrown when an application attempts to use null where an object is required.
    ArrayIndexOutOfBoundsException Thrown to indicate that an array has been accessed with an illegal index.
    ClassCastException Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance.
    IllegalArgumentException Thrown to indicate that a method has been passed an illegal or inappropriate argument.
    ArithmeticException Thrown when an exceptional arithmetic condition has occurred (e.g., division by zero).
    NumberFormatException Thrown to indicate that the application has attempted to convert a string to a numeric type, but the string does not have the appropriate format.
    IllegalStateException Thrown to indicate that a method has been invoked at an illegal or inappropriate time.
    NoSuchElementException Thrown by various accessor methods to indicate that the element being requested does not exist.
    IndexOutOfBoundsException Thrown to indicate that an index of some sort (e.g., array, string) is out of range.
    UnsupportedOperationException Thrown to indicate that the requested operation is not supported.
    ConcurrentModificationException Thrown by methods that have detected concurrent modification of an object when such modification is not permissible.
    SecurityException Thrown by the security manager to indicate a security violation.

     

    Key Differences Summarized:

    Feature Checked Exceptions Unchecked Exceptions
    Compile-time Checked Not checked
    Handling Mandatory Optional
    Inheritance Exception (excluding RuntimeException) RuntimeException or Error
    Typical Causes External factors Programming errors

     

    When to Use Which:

    • Use checked exceptions for conditions that are reasonably expected and should be handled to ensure program stability (e.g., file I/O, database access).
    • Use unchecked exceptions for programming errors that are typically considered unrecoverable (e.g., null pointer dereferences, array index out-of-bounds errors).

     

     


    End of the lesson….enjoy learning

     

     

    Student Ratings and Reviews

     

     

     

    There are no reviews yet. Be the first one to write one.

     

     

    Submit a Review

     

     

    Layer 1
    Login Categories