Java Exception Handling

Exception Handling in Java

In programming, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. It usually signals that something has gone wrong, such as trying to divide by zero, accessing an array out of bounds, or reading a file that doesn’t exist.

Why Use Exception Handling?

Exception handling allows your program to deal with unexpected situations (exceptions) gracefully, without crashing. This makes your programs more robust and user-friendly.

The try/catch Block

In Java, exceptions are handled using try and catch blocks. Here’s a simple structure:

try {
    // Code that might throw an exception
} catch (Exception e) {
    // Code that runs if an exception occurs
}

The code that might throw an exception goes inside the try block.
The catch block contains the code that runs if an exception is thrown. The Exception e part allows you to capture information about the exception.

Example 1: Handling Division by Zero

We’ll create a simple program to understand this better. The program will attempt to divide two numbers entered by the user. If the user enters zero as the second number, it will cause an ArithmeticException.

import java.util.Scanner;

class Program {
    public static void main(String[] args) {
        try {
            Scanner scanner = new Scanner(System.in);
            System.out.println(“Enter the first number: “);
            int num1 = scanner.nextInt();
            System.out.println(“Enter the second number: “);
            int num2 = scanner.nextInt();

            // Attempt to divide the numbers
            int result = num1 / num2;
            System.out.println(“The result is: ” + result);
            } catch (ArithmeticException e) {
            System.out.println(“Error: ” + e);
        }
    }
}

You can see an error in the below image. if you divide 10 by 0. the system will give you an error

Explanation:

import java.util.Scanner;

This line imports the Scanner class from the java.util package. Scanner is a utility class in Java that allows reading user input from various sources, including the console.

class Program {

Here, we define a class named Program. In Java, all code must be inside a class, which acts as a blueprint for creating objects. Since the program starts execution from this class, it contains the main method.

public static void main(String[] args) {

This is the main method, the entry point of any Java application. Let’s break down its components:
        ○ public: This keyword makes the main method accessible from anywhere.
        ○ static: It allows the method to be run without creating an instance of the class.
        ○ void: Indicates that this method does not return any value.
        ○ String[] args: Accepts an array of String arguments from the command line, though it’s unused here.

try {

This line starts a try block, where code that might throw an exception is placed. It helps in handling unexpected situations, such as dividing by zero.

Scanner scanner = new Scanner(System.in);

This creates a Scanner object named scanner that reads input from System.in, which refers to the standard input (usually the keyboard).

System.out.println(“Enter the first number: “);

This line prints the message “Enter the first number: ” to prompt the user for input.

int num1 = scanner.nextInt();

scanner.nextInt() reads an integer entered by the user and assigns it to the variable num1.

System.out.println(“Enter the second number: “);

This prints “Enter the second number: ” to prompt the user for a second input.

int num2 = scanner.nextInt();

scanner.nextInt() reads another integer input and stores it in num2.

int result = num1 / num2;

This line performs division using num1 and num2 and stores the result in the result variable. If num2 is zero, this line will throw an ArithmeticException (as division by zero is undefined).

System.out.println(“The result is: ” + result);

If no exception occurs, this line prints the result of the division.

} catch (ArithmeticException e) {

If an ArithmeticException (like division by zero) occurs, control is transferred here. The catch block catches the exception and prevents the program from crashing.

System.out.println(“Error: ” + e);

This prints a user-friendly message indicating that an error occurred, along with the exception details.

Example 2: Handling ArrayIndexOutOfBoundsException

This example shows handling an ArrayIndexOutOfBoundsException when accessing an array element that doesn’t exist.

class IndexOutOfBoundsExample {
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println(“Error: ” + e);
        }
    }
}

You can see an error in the below image.

Explanation:

class IndexOutOfBoundsExample {

This defines a class named IndexOutOfBoundsExample. In Java, code must be organised within classes, and this one is specifically designed to demonstrate handling an ArrayIndexOutOfBoundsException.

public static void main(String[] args) {

This is the main method, the entry point of any Java application. It is:
        ○ public: accessible from anywhere.
        ○ static: can be called without creating an instance of the class.
        ○ void: returns no value.
        ○ String[] args: accepts an array of String arguments from the command line, though they are unused here.

try {

This begins a try block where code that may potentially throw an exception is placed. It allows us to catch exceptions and prevent the program from crashing due to errors.

int[] numbers = {1, 2, 3};

This line declares and initialises an integer array named numbers with three elements: 1, 2, and 3.

System.out.println(numbers[5]);

This line attempts to access the element at index 5 in the numbers array. Since the array only has three elements (at indices 0, 1, and 2), this causes an ArrayIndexOutOfBoundsException because index 5 is out of the array’s bounds.

} catch (ArrayIndexOutOfBoundsException e) {

This catch block catches the specific ArrayIndexOutOfBoundsException. When this exception is thrown in the try block, control is transferred here, allowing us to handle the error gracefully.

System.out.println(“Error: ” + e);

This prints an error message to the console along with the exception details (e). The message will describe the exception that occurred, indicating an attempt to access an invalid index in the array.

Example 3: Handling NumberFormatException

This example handles a NumberFormatException when trying to convert a non-numeric string to an integer.

class FormatExceptionExample {
    public static void main(String[] args) {
        try {
            String input = “abc”;
            int number = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            System.out.println(“Error: ” + e);
        }
    }
}

You can see an error in the below image.

Explanation:

class FormatExceptionExample {

This defines a class named FormatExceptionExample. In Java, all code must be inside classes, and this one is specifically created to demonstrate handling a NumberFormatException.

public static void main(String[] args) {

This is the main method, the entry point for the program. Let’s break down its components:
      ○ public: allows access from any part of the program.
      ○ static: enables the method to be called without creating an instance of the class.
      ○ void: indicates that the method does not return a value.
      ○ String[] args: allows passing arguments from the command line as a String array, though these arguments are not used
         here.

try {

This line starts a try block, which contains code that may throw an exception. The purpose of a try block is to catch exceptions that might disrupt the program’s flow, enabling us to handle them gracefully.

String input = “abc”;

This declares a String variable named input and assigns it the value “abc”. Here, “abc” is a non-numeric string, which will cause an issue in the following line, where we attempt to parse it as an integer.

int number = Integer.parseInt(input);

This line attempts to convert the input string (“abc”) to an integer using Integer.parseInt(). However, since “abc” is not a valid integer, this will throw a NumberFormatException. This exception is handled by the catch block below.

} catch (NumberFormatException e) {

This catch block catches the specific NumberFormatException. When this exception is thrown in the try block, control is transferred here, allowing the program to handle the error gracefully rather than crashing.

System.out.println(“Error: ” + e);

This prints an error message along with the exception details (e). The exception message will typically describe the nature of the error, indicating that the program attempted to convert a non-numeric string to an integer.

Course Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

The training covers Java exception handling, including concepts, syntax, and practical applications.

Yes, it includes examples demonstrating how to use try, catch, and finally blocks to manage exceptions.

Yes, exercises involve creating programs that handle various exceptions to understand their usage in different scenarios.

Yes, it’s designed for beginners with clear explanations and step-by-step examples.

A Java IDE like Eclipse, IntelliJ IDEA, or an online compiler will suffice.

Yes, it covers how exception handling allows programs to deal with unexpected situations gracefully, enhancing robustness and user-friendliness.

Yes, the training is self-paced and accessible online anytime.

Yes, it explains the distinctions and appropriate use cases for checked and unchecked exceptions.

It typically takes a few hours to complete, depending on your learning pace.

Yes, this Java Exception Handling training is completely free on Iqra Technology Academy’s website.