Thursday, 11 September 2025

Mastering Exception Handling in Java: From Basics to Best Practices

Quote
"If you can change your mind, you can change your life."

Exception Handling

 

An exception is an unwanted or unexpected event that occurs during the execution of a program.
For example: runtime errors like dividing a number by zero.

To handle such situations, we use Exception Handling, which provides an alternative way to continue the normal flow of the program instead of stopping it abruptly.

Exception Herarichy





Difference between Exception and Error 


Types of Exceptions in Java

1.CompileTime Exception or (Checked Exception)

2.Runtime Exception or (Unchecked Exception)

CompileTime Exception or (Checked Exception)

  • Exception Checked by the Compiler and handled with (try-catch throws).
  • A checked exception is an exception that the Java compiler checks at compile-time.
  • 👉 Examples of checked exceptions:

    • IOException

    • SQLException

    • FileNotFoundException 

    One way to handle checked exceptions is by catching and handling them inside the method itself using a try-catch block.

output:If File is Missing
Error: The file was not found.
Output:If File is Not Missing
File opened successfully.

🔎 Explanation:

  1. FileReader tries to open test.txt.

  2. If the file does not exist, a FileNotFoundException (checked exception) is thrown.

  3. The try-catch block catches the exception and prints an error message instead of stopping the program.

  4. This way, the program handles the exception inside the method itself — no need to declare throws.

2.RunTimeException/Unchecked Exception

  • While Compiler not checked by compiler, Occurs during Program execution.
  • We can write code with runtime exceptions without handling them.

  • If they occur, they happen during program execution (runtime), not at compile time.

for example: ArithmeticException

        class RuntimeExceptionExample1 {
    public static void main(String[] args) {
        int number = 10;
        int result = number / 0; // Runtime error: divide by zero
        System.out.println("Result: " + result);
    }
}

 output :- Exception in thread "main" java.lang.ArithmeticException: / by zero.

Difference between CheckedException & UncheckedException



 We can Handle the Exception using 5 keywords.

1.try

2.catch

3.finally

4.throw

5.throws

try-catch

Syntax of try-catch

try {

    // Risky Code

} catch (ExceptionType e) {

    // Code to handle the exception

}

Note: For print exception() methods.

  catch (ExceptionType e) 

  • exceptionName
  • description
  • stackTrace(line) 


    


Example:

class TryCatchExample {

    public static void main(String[] args) {

        try {

            int number = 10;

            int result = number / 0; 

           // This will throw ArithmeticException

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

        } catch (ArithmeticException e) {

            System.out.println("Error: Cannot divide by zero.");

        }

    }

}

Output:

Error: Cannot divide by zero.

🔎 Explanation

  1. try block → Place the code that might throw an exception.

  2. catch block → Handles the exception if it occurs.

  3. If no exception occurs → catch block is skipped.

3.finally
  • A finally block always runs after try and any matching catch blocks — used for cleanup (closing files, releasing locks, etc.)
  • It runs whether an exception was handled or not. 
Syntax of finally

  try {
    // risky code
} catch (SomeException e) {
    // handle
} finally {
    // cleanup — always executes (usually)
}

Note:

You can have at most one finally for a try block. catch blocks are optional when you have finally.

Syntax of finally without catch

  try {
    // risky code
} finally {
    // cleanup — always executes (usually)
}

Some Example of finally

try {
    System.out.println("In try");
} catch (Exception e) {
    System.out.println("In catch");
} finally {
    System.out.println("In finally");
}


Output:
In try
In finally

Note: finally runs even though no exception happened.

Disturbs the execution of Finally block not execute finally.

1. System.exit() is called

    class FinallyExample {
    public static void main(String[] args) {
        try {
            System.out.println("In try block");
            System.exit(0); // JVM shuts down immediately
        } finally {
            System.out.println("In finally block");
        }
    }
}

output:
In try block

Note: finally is skipped because JVM shuts down.

2. JVM crashes
  • If the program crashes due to a native error or external system failure (e.g., OutOfMemoryError in some cases, or hardware failure), the finally block won’t run.
3. Infinite loop or force kill inside try

       try {
    while(true) {}  // Infinite loop
} finally {
    System.out.println("Will never reach here");
}

Note: 👉 Here, finally never executes because control never leaves the try.

4. The death of a thread.

Difference between final,finally,finalize



4.Throw Keyword
  • Actualy throwing Exception Object.
  • Customize Exception.
  • Used inside method to throw exception object.
Example of using throw keyword

  class ThrowExample {
    public static void main(String[] args) {
        int age = 15;

        if (age < 18) {
            // Manually creating and throwing an exception object
            throw new ArithmeticException("Not eligible to vote");
        }

        System.out.println("Eligible to vote");
    }
}


output:
Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote.

Note:
  • The throw keyword is used to manually create an exception object and pass it to the JVM for handling.
  • We can't write any statement after throw.
  • Exception handling by try-catch.
  • We can throw only one exception at a time using throw.
  • Once thrown, the JVM passes that object to the runtime system to handle it.
5.Throws keyword
  • It is used to declare that a method may throw exception.
  • It is Keyword (in method signature).
Example of using throws keyword

     import java.io.*;

    class ThrowsExample {
    public static void main(String[] args) {
        try {
            readFile(); 
         // must handle exception here
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Method declares it may throw IOException
    public static void readFile() throws IOException {
        FileReader fr = new FileReader("test.txt");
        System.out.println("File opened successfully");
    }
}
output: If the file exists
   File opened successfully
output: If the file not exist
Error: test.txt (No such file or directory)

Note:
  • It does not handle the exception itself, but passes the     responsibility to the caller.
  • The caller must handle it (with try-catch) or declare it again  using throws.
Difference between throw & throws keyword















No comments:

Post a Comment

Mastering Exception Handling in Java: From Basics to Best Practices

Quote "If you can change your mind, you can change your life." Exception Handling   An exception is an unwanted or unexpected eve...