Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Tuesday, March 4, 2025

Exception Handling in Java


Java provides a structured way to handle exceptions using:

  1. try-catch block
  2. finally block
  3. throws keyword
  4. throw keyword

1. try-catch Block

public class TryCatchExample {

    public static void main(String[] args) {

        try {

            int result = 10 / 0;  // ArithmeticException

        } catch (ArithmeticException e) {

            System.out.println("Cannot divide by zero: " + e.getMessage());

        }

    }

}


2. finally Block (Always Executes)

public class FinallyExample {

    public static void main(String[] args) {

        try {

            int num = Integer.parseInt("ABC");  // NumberFormatException

        } catch (NumberFormatException e) {

            System.out.println("Invalid number format.");

        } finally {

            System.out.println("This block always executes.");

        }

    }

}


3. throws Keyword (Declaring an Exception)

import java.io.*;

 

public class ThrowsExample {

    public static void readFile() throws IOException {

        FileReader file = new FileReader("file.txt");

    }

 

    public static void main(String[] args) {

        try {

            readFile();

        } catch (IOException e) {

            System.out.println("Handled IOException.");

        }

    }

}


4. throw Keyword (Explicitly Throw an Exception)

public class ThrowExample {

    static void checkAge(int age) {

        if (age < 18) {

            throw new IllegalArgumentException("Age must be 18 or above.");

        }

    }

 

    public static void main(String[] args) {

        checkAge(16);

    }

}


Custom Exceptions in Java

You can create user-defined exceptions by extending the Exception class.

class MyException extends Exception {

    public MyException(String message) {

        super(message);

    }

}

 

public class CustomExceptionExample {

    public static void main(String[] args) {

        try {

            throw new MyException("This is a custom exception");

        } catch (MyException e) {

            System.out.println(e.getMessage());

        }

    }

}


Conclusion

  • Java provides a well-structured exception hierarchy under the Throwable class.
  • Checked exceptions must be handled at compile-time, while unchecked exceptions occur at runtime.
  • Errors are critical system failures that should not be caught.
  • Java provides try-catch, finally, throw, and throws to handle exceptions properly.
  • Custom exceptions allow defining application-specific error handling mechanisms.


No comments:

Post a Comment