Java Tutorials
  • Introduction to Java
    • What is Java?
    • History and Features of Java
    • Java Virtual Machine (JVM) and Bytecode
    • Why Java?
  • Setting up Java Development Environment
    • Installing Java Development Kit (JDK)
    • JDK vs JRE
    • Setting up IDE (Eclipse, IntelliJ, NetBeans) or Text Editor (VS Code, Sublime Text)
  • Basic Java
    • First Java Program : Hello World
    • Variable
    • Data Type
    • Constant
    • Date and Format
    • Operator
    • Condition
    • Looping
    • Function
    • Variadic Function
    • Enums
    • Array
    • Collection
    • Exception and Exception Handling
    • Naming Convention
  • Object Oriented Programming (OOP)
    • Classes and Objects
    • Inheritance and Polymorphism
    • Encapsulation and Abstraction
  • File Handling
    • Reading and Writing Binary File
    • Reading and Writing Text File
    • Serialization and Deserialization
  • Multithreading
    • Creating and Running Threads
    • Synchronization
    • Thread Pools and Executors
  • Collections API
    • Sorting and Comparable
    • Searching and Comparator
  • Java Database Connectivity (JDBC)
    • Introduction and Life Cycle
    • Connection to Database (MySQL)
    • Downloading JDBC Drivers for Various Databases
    • Maven and Gradle JDBC Drivers for Various Databases
    • JDBC URL Formats
    • Statement and PreparedStatement
    • CallableStatement
    • Selecting Data using JDBC
    • Inserting Data using JDBC
    • Updating Data using JDBC
    • Deleting Data using JDBC
    • Invoking Function and Stored Procedure using JDBC
  • Lambda
    • Introduction to Lambda Expressions
    • Functional Interface
    • Filtering, Mapping, Reducing
    • Lambda Expressions in Collections
    • Method References
    • Functional Programming Concepts
    • Stream API
    • Error Handling in Lambda Expressions
    • Optional in Functional Programming
    • Parallel Processing with Lambda
    • Functional Programming Patterns
    • Advanced Topics in Lambda Expressions
    • Best Practices and Design Patterns
    • Real-World Use Cases and Examples
Powered by GitBook
On this page
  1. Basic Java

Exception and Exception Handling

In Java, an exception is an event that disrupts the normal flow of a program's instructions during its execution. Exceptions can occur due to various reasons such as incorrect input, division by zero, or attempting to access an array element outside its bounds. Exception handling in Java allows you to gracefully deal with these unexpected events, preventing program crashes and providing a way to handle errors effectively.

Types of Exceptions:

  1. Checked Exceptions: Checked exceptions in Java are exceptions that are checked at compile time. This means that the Java compiler ensures that these exceptions are either caught or declared in the method signature using the throws keyword. Checked exceptions are typically used for conditions that are outside the control of the program, such as file I/O errors or network connectivity issues.

  2. Unchecked Exceptions (Runtime Exceptions): Unchecked exceptions, also known as runtime exceptions, are exceptions that are not checked at compile time. Unlike checked exceptions, which the compiler forces you to handle, unchecked exceptions can occur at runtime and are not required to be caught or declared in the method signature. Unchecked exceptions are typically caused by programming errors, such as accessing an array index out of bounds or attempting to divide by zero.

Exception Handling in Java:

Java provides keywords try, catch, finally, and throw to handle exceptions.

  • try: The try block contains the code that might throw an exception.

  • catch: The catch block catches and handles the exception thrown in the try block.

  • finally: The finally block contains code that will be executed regardless of whether an exception occurs or not.

  • throw: The throw keyword is used to throw a specific exception explicitly.

Example Code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class ExceptionHandlingExample {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int result = 0;

        try {
            System.out.print("Enter a number: ");
            int num = scanner.nextInt();

            result = 10 / num; // Division operation that might throw ArithmeticException
        } catch (InputMismatchException e) {
            System.out.println("Invalid input. Please enter a number.");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        } finally {
            System.out.println("This block always executes.");
            scanner.close();
        }

        System.out.println("Result: " + result);
    }
}

Explanation:

  1. The program attempts to read an integer from the user.

  2. If the user enters a non-integer value, it catches InputMismatchException and prints an error message.

  3. If the user enters 0 (for division), it catches ArithmeticException and prints an error message.

  4. The finally block always executes, allowing you to close resources or execute essential cleanup code.

  5. Regardless of exceptions, the program continues to execute after the try-catch blocks.

When you run this Java program:

  • If you enter a non-integer value, it will catch InputMismatchException.

  • If you enter 0, it will catch ArithmeticException.

  • In either case, the program will execute the finally block before termination.

This example demonstrates how to handle exceptions in Java and how the try, catch, and finally blocks work together to ensure the program doesn't crash unexpectedly.

How to Handle Checked Exceptions:

  1. Catching Checked Exceptions: You can catch checked exceptions using try and catch blocks. If a method throws a checked exception, it must be either caught or declared in the method signature.

    try {
        // Code that might throw a checked exception
    } catch (ExceptionType e) {
        // Handling the exception
    }
  2. Declaring Checked Exceptions: If a method may throw a checked exception, you should declare it in the method signature using the throws keyword. This informs the calling method that it needs to handle the exception.

    public void myMethod() throws SomeCheckedException {
        // Code that might throw SomeCheckedException
    }

Example Code with Checked Exception:

import java.io.FileReader;
import java.io.IOException;

public class CheckedExceptionExample {

    public static void main(String[] args) {
        try {
            // Attempting to read a file that might not exist
            FileReader fileReader = new FileReader("nonexistent-file.txt");
            // Code to read the file
        } catch (IOException e) {
            // Handling the IOException
            System.out.println("An error occurred: " + e.getMessage());
        }
    }
}

Explanation:

In this example, the FileReader constructor may throw an IOException if the specified file does not exist. The code inside the try block attempts to create a FileReader object for a file that might not be present.

  • The try block contains the code that might throw the checked exception (IOException in this case).

  • The catch block catches the IOException and handles it by printing an error message.

  • Since IOException is a checked exception, it must be caught or declared using the throws keyword in the method signature.

When you run this Java program, it will handle the IOException gracefully without crashing, even if the file does not exist. This is an essential mechanism for building robust Java applications.

Common Unchecked Exceptions in Java:

  1. ArithmeticException: Thrown when an arithmetic operation (like division) has an exceptional condition.

  2. NullPointerException: Thrown when trying to access an object that is null.

  3. ArrayIndexOutOfBoundsException: Thrown when attempting to access an array element at an invalid index.

  4. NumberFormatException: Thrown when trying to convert a string to a numeric type, but the string does not have the appropriate format.

Handling Unchecked Exceptions:

Unchecked exceptions are not required to be caught or declared. However, it's good practice to handle them if you anticipate them in your code to prevent unexpected program termination.

Example Code with Unchecked Exception:

public class UncheckedExceptionExample {

    public static void main(String[] args) {
        try {
            int result = 10 / 0; // ArithmeticException: Attempting to divide by zero
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }

        String str = null;
        try {
            int length = str.length(); // NullPointerException: Trying to access length of a null object
        } catch (NullPointerException e) {
            System.out.println("Error: " + e.getMessage());
        }

        try {
            int[] numbers = {1, 2, 3};
            int value = numbers[5]; // ArrayIndexOutOfBoundsException: Attempting to access an out-of-bounds index
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Explanation:

In this example, the program deliberately creates scenarios where unchecked exceptions (ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException) occur:

  1. int result = 10 / 0;: This line attempts to divide by zero, resulting in an ArithmeticException.

  2. int length = str.length();: str is null, so trying to access its length() method results in a NullPointerException.

  3. int value = numbers[5];: numbers array does not have an element at index 5, leading to an ArrayIndexOutOfBoundsException.

Each scenario is caught in a try-catch block, and an error message is printed. Handling these exceptions prevents the program from crashing unexpectedly, allowing it to continue executing the subsequent code.

PreviousCollectionNextNaming Convention

Last updated 1 year ago