Exception Handling in Java – A Complete Guide from Basics to Advanced

 In Java programming, errors can occur at any time during program execution. These errors may be caused by invalid input, unavailable resources, logical mistakes, or system failures. If not handled properly, such errors can crash the program and disrupt normal execution.

Exception handling in Java is a powerful mechanism that allows developers to handle runtime errors gracefully. Instead of terminating the program abruptly, Java provides structured ways to detect, handle, and recover from errors.

This blog explains exception handling in Java from beginning to end, covering all keywords, concepts, flow diagrams, and best practices in detail.

Exception Handling in Java

What Is an Exception in Java?

An exception is an unwanted or unexpected event that occurs during program execution and disrupts the normal flow of instructions.

Examples:

  • Dividing a number by zero
  • Accessing an invalid array index
  • Opening a file that does not exist
  • Using a null object reference

In Java, exceptions are treated as objects, and all exceptions are derived from the Throwable class.


Exception Hierarchy in Java

Java follows a hierarchical structure for exception handling:

Types of Exceptions in Java

Types of Exceptions in Java

1. Checked Exceptions

Checked exceptions are checked at compile time. The programmer must handle them using try-catch or declare them using throws.

Examples:

  • IOException
  • SQLException
  • FileNotFoundException


2. Unchecked Exceptions

Unchecked exceptions occur at runtime and are not checked by the compiler.

Examples:

  • ArithmeticException
  • NullPointerException
  • ArrayIndexOutOfBoundsException

3. Errors

Errors represent serious system-level issues and should not be handled by applications.

Examples:

  • OutOfMemoryError
  • StackOverflowError


Java Exception Handling Keywords

Java provides five important keywords for handling exceptions:

1. try Block

Definition

The try block is used to wrap code that may cause an exception. Java monitors this block for runtime errors.


Syntax

try { // code that may cause exception }

Example

try { int result = 10 / 0; }

Flow Diagram – try

StartExecute try block ↓ Exception occurs? ┌─────────┐ │ No │ → Continue execution └─────────┘ │ Yes ↓ Exception object created

2. catch Block

Definition

The catch block is used to handle exceptions thrown by the try block. Each catch block handles a specific type of exception.


Syntax

catch (ExceptionType e) { // exception handling code }

Example

try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Division by zero is not allowed"); }

Flow Diagram – catch

Exception thrown ↓ Check for matching catch block ↓ Match found? ┌─────────┐ │ Yes │ → Execute catch block └─────────┘ │ No ↓ Program terminates abnormally

3. finally Block

Definition

The finally block always executes whether an exception occurs or not. It is mainly used for resource cleanup.


Syntax

finally { // cleanup code }

Example

try { int a = 10 / 2; } catch (Exception e) { System.out.println(e); } finally { System.out.println("Finally block executed"); }

Flow Diagram – finally

try block execution ↓ Exception occurs or not ↓ catch block executes (if needed) ↓ finally block executes ↓ Program continues

4. throw Keyword

Definition

The throw keyword is used to explicitly throw a single exception manually during program execution.

It is commonly used for:

  • Input validation
  • Business rule enforcement
  • Custom exception handling


Syntax

throw new ExceptionType("Error message");

Example

int age = 15; if (age < 18) { throw new ArithmeticException("Not eligible to vote"); }

Flow Diagram – throw

Condition check ↓ Condition true? ┌─────────┐ │ Yes │ → throw exception └─────────┘ ↓ Exception object created ↓ Control transferred to catch block

5. throws Keyword

Definition

The throws keyword is used to declare exceptions that a method may pass to the calling method. It does not handle the exception but shifts responsibility.


Syntax

returnType methodName() throws ExceptionType { }

Example

void readFile() throws IOException { FileReader file = new FileReader("data.txt"); }

Flow Diagram – throws

Method execution ↓ Exception occurs ↓ Method does not handle exceptionException passed to calling method

throw vs throws

Featurethrowthrows
Used to throw exceptionYesNo
Used in method signatureNoYes
Throws single exceptionYesNo
Used inside methodYesNo

Multiple Catch Blocks

Java allows multiple catch blocks to handle different exceptions separately.

try { int[] arr = new int[5]; arr[10] = 50; } catch (ArithmeticException e) { System.out.println("Arithmetic error"); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index error"); }

Custom Exceptions in Java

Java allows developers to create user-defined exceptions.

class InvalidAgeException extends Exception { InvalidAgeException(String msg) { super(msg); } }

Custom exceptions improve code readability and domain-specific error handling.


Best Practices for Exception Handling

  • Catch specific exceptions
  • Avoid empty catch blocks
  • Use meaningful error messages
  • Do not use exceptions for normal logic
  • Always clean up resources
  • Log exceptions properly

Post a Comment

0 Comments