w1coding.comAll tutorials

Java Exception

Java lessons
  1. Environment Setup
  2. Introduction
  3. Variables
  4. Control
  5. Loops
  6. Arrays
  7. Methods
  8. OOP
  9. Contractors
  10. Inheritance
  11. Polymorphism
  12. Abtract
  13. Interfaces
  14. Constructors
  15. Static
  16. Exception
  17. Collections
  18. Lambda
  19. Streams
  20. Strings
  21. Date
  22. Interface
  23. Inheritance
  24. Polymorphism
  25. Exception
  26. File

Java Exception Handling

Exception handling is a mechanism to handle runtime errors, allowing the program to continue its execution without abrupt termination. Java provides try, catch, and finally blocks to handle exceptions.

Try and Catch Block

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;  // This will throw an ArithmeticException
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
    

The try block is used to write code that might throw an exception. The catch block catches the exception and handles it. In this example, dividing by zero throws an ArithmeticException, which is caught and handled.

Finally Block

public class ExceptionHandlingExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            System.out.println("This block always runs");
        }
    }
}
    

The finally block is always executed, regardless of whether an exception is thrown or not. It is typically used to close resources like files or network connections.