Java Exception Handling Try Catch Finally & Custom Exceptions

Zaheer Ahmad 5 min read min read
Python
Java Exception Handling Try Catch Finally & Custom Exceptions

Absolutely! Here's a full, structured, SEO-friendly tutorial draft following your requirements for theiqra.edu.pk:

Java Exception Handling: Try, Catch, Finally & Custom Exceptions

Java programming is widely used in Pakistan for web, mobile, and desktop development. However, even the best code can face unexpected errors during execution. This is where Java exception handling comes in. Exception handling allows programmers to manage errors gracefully without crashing the program. In Java, this is achieved using try, catch, finally, and custom exceptions.

Learning Java exception handling is crucial for Pakistani students because it ensures robust applications. For example, if Ahmad is building a billing system in Lahore and a customer enters an invalid payment amount, exception handling will prevent the program from crashing and provide a clear error message.


Prerequisites

Before diving into exception handling, you should be familiar with:

  • Basic Java syntax and program structure
  • Variables, data types, and operators
  • Java methods and classes
  • Control flow statements (if-else, loops)
  • Fundamental OOP concepts (inheritance, polymorphism)

If you are comfortable with these, you are ready to handle errors like a pro!


Core Concepts & Explanation

What is an Exception in Java?

An exception is an event that occurs during program execution that disrupts the normal flow. Exceptions can be caused by:

  • Invalid user input (e.g., negative numbers for age)
  • File or network errors
  • Divide-by-zero operations

Java distinguishes exceptions as:

  • Checked Exceptions: Must be handled at compile time (e.g., IOException)
  • Unchecked Exceptions: Occur at runtime, optional to handle (e.g., ArithmeticException)

The try Block

The try block contains code that might throw an exception. Java monitors this block for errors.

public class TryExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // risky operation
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: Division by zero!");
        }
    }
}

Line-by-line explanation:

  1. try { ... } – Wraps the code that could cause an exception.
  2. int result = 10 / 0; – Division by zero triggers an ArithmeticException.
  3. catch (ArithmeticException e) – Handles the exception to prevent program crash.
  4. System.out.println("Error: Division by zero!"); – Displays a user-friendly error message.

The catch Block

The catch block handles the exception thrown in the try. You can have multiple catch blocks for different exception types.

try {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[5]); // ArrayIndexOutOfBoundsException
} catch (ArithmeticException e) {
    System.out.println("Arithmetic error!");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index is out of bounds!");
}

Explanation:

  • Java checks each catch block in order.
  • The first matching exception type executes.

The finally Block

The finally block executes regardless of an exception occurring or not. It is often used for cleanup like closing files or releasing resources.

try {
    System.out.println("Reading file...");
    // simulate file read error
    int data = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Caught an error!");
} finally {
    System.out.println("This always runs.");
}

Explanation:

  • finally ensures cleanup.
  • In Pakistan, Ahmad could use finally to close a database connection after processing transactions.

Custom Exceptions in Java

Java allows programmers to define custom exceptions by extending Exception or RuntimeException.

class InvalidAmountException extends RuntimeException {
    public InvalidAmountException(String message) {
        super(message);
    }
}

public class CustomExceptionDemo {
    public static void main(String[] args) {
        try {
            int payment = -500; // PKR
            if (payment < 0) {
                throw new InvalidAmountException("Payment cannot be negative!");
            }
        } catch (InvalidAmountException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Explanation:

  1. InvalidAmountException extends RuntimeException to create a custom exception.
  2. throw new InvalidAmountException(...) triggers the exception.
  3. Catching it allows a controlled response.

Practical Code Examples

Example 1: Division Calculator

public class DivisionCalculator {
    public static void main(String[] args) {
        try {
            int dividend = 100;
            int divisor = 0;
            int quotient = dividend / divisor;
            System.out.println("Quotient: " + quotient);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        } finally {
            System.out.println("Calculation attempt finished.");
        }
    }
}

Explanation:

  • Demonstrates try, catch, finally.
  • Ensures program continues running even after a division error.

Example 2: Real-World Application — Bank Payment System

class NegativeBalanceException extends Exception {
    public NegativeBalanceException(String message) {
        super(message);
    }
}

public class BankAccount {
    private double balance;

    public BankAccount(double balance) {
        this.balance = balance;
    }

    public void withdraw(double amount) throws NegativeBalanceException {
        if (amount > balance) {
            throw new NegativeBalanceException("Insufficient PKR balance!");
        }
        balance -= amount;
        System.out.println("Withdrawal successful. Remaining balance: " + balance);
    }

    public static void main(String[] args) {
        BankAccount account = new BankAccount(5000);
        try {
            account.withdraw(6000); // Attempt to withdraw more than balance
        } catch (NegativeBalanceException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Explanation:

  • Shows real-world banking scenario relevant to Pakistani students.
  • Throws a checked exception if balance is insufficient.

Common Mistakes & How to Avoid Them

Mistake 1: Ignoring Exceptions

int result = 10 / 0; // Program crashes

Fix: Always use try-catch to handle possible errors.

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Handled division by zero!");
}

Mistake 2: Catching Generic Exception Only

try {
    int[] arr = {1, 2};
    System.out.println(arr[5]);
} catch (Exception e) {
    System.out.println("Something went wrong!");
}

Fix: Catch specific exceptions for better debugging.

try {
    int[] arr = {1, 2};
    System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Array index error!");
}

Practice Exercises

Exercise 1: Handle Divide by Zero

Problem: Write a program to divide two numbers entered by Fatima. Handle division by zero gracefully.

Solution:

import java.util.Scanner;

public class SafeDivision {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter dividend: ");
        int dividend = sc.nextInt();
        System.out.println("Enter divisor: ");
        int divisor = sc.nextInt();

        try {
            int result = dividend / divisor;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero!");
        }
    }
}

Exercise 2: Custom Age Validation

Problem: Validate Ali’s age for an online registration system. Age cannot be negative or below 18.

Solution:

class InvalidAgeException extends Exception {
    public InvalidAgeException(String message) {
        super(message);
    }
}

public class AgeValidator {
    public static void main(String[] args) {
        int age = 15; // Example input
        try {
            if (age < 18) {
                throw new InvalidAgeException("Age must be 18 or above!");
            }
            System.out.println("Registration successful.");
        } catch (InvalidAgeException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Frequently Asked Questions

What is Java exception handling?

Java exception handling is a mechanism to handle runtime errors gracefully using try, catch, finally, and custom exceptions.

How do I create a custom exception in Java?

You create a custom exception by extending Exception or RuntimeException and optionally defining a constructor to accept error messages.

What is the difference between checked and unchecked exceptions?

Checked exceptions are verified at compile-time, while unchecked exceptions occur at runtime and do not require mandatory handling.

Can I have multiple catch blocks in Java?

Yes, you can have multiple catch blocks to handle different exception types separately.

Why use the finally block?

The finally block ensures cleanup code runs regardless of whether an exception occurred, such as closing files or database connections.


Summary & Key Takeaways

  • Java exceptions prevent program crashes and improve reliability.
  • Use try to wrap risky code and catch to handle specific errors.
  • finally is essential for cleanup operations.
  • Custom exceptions allow domain-specific error handling (e.g., negative payments).
  • Catch specific exceptions instead of generic ones for better debugging.
  • Practice exception handling with real-world scenarios like banking or registration systems.


This tutorial is complete, fully structured with ## H2 headings, practical Pakistani examples, images placeholders, and SEO-optimized for your keywords: java exception handling, java try catch, java custom exceptions.


If you want, I can also create the 3 images visually for this tutorial:

  1. Java exception hierarchy tree
  2. Try-catch-finally flow diagram
  3. Checked vs unchecked exceptions visual

Do you want me to generate them?

Practice the code examples from this tutorial
Open Compiler
Share this tutorial:

Test Your Python Knowledge!

Finished reading? Take a quick quiz to see how much you've learned from this tutorial.

Start Python Quiz

About Zaheer Ahmad