Exception handling

Exception handling

Exception handling is a programming construct that allows a program to detect, handle and recover from errors that occur during runtime. An exception is an error or abnormal condition that occurs while a program is running, such as an invalid user input or a file not found.

In Java, exceptions are represented by objects. When an exception is thrown, the JVM creates an exception object and then looks for an exception handler to handle the exception. If no exception handler is found, the program terminates and a stack trace is printed to the console.

To handle exceptions in Java, you can use the try-catch block. The try block contains the code that might throw an exception, and the catch block contains the code that handles the exception. Multiple catch blocks can be used to handle different types of exceptions.

For example:

try {

    // code that might throw an exception

    int x = 5 / 0; // division by zero

} catch (ArithmeticException e) {

    // code to handle the exception

    System.out.println(“An arithmetic exception occurred: ” + e.getMessage());

}

In this example, the code in the try block tries to divide the number 5 by zero, which is not allowed and will throw an ArithmeticException. The catch block catches the exception and prints a message to the console.

Java also provides a finally block that can be used to execute code regardless of whether an exception is thrown or not. The code in the finally block is executed after the try and catch blocks, whether an exception is thrown or not.

For example:

try {

    // code that might throw an exception

    int x = 5 / 0; // division by zero

} catch (ArithmeticException e) {

    // code to handle the exception

    System.out.println(“An arithmetic exception occurred: ” + e.getMessage());

} finally {

    // code to be executed regardless of whether an exception is thrown or not

    System.out.println(“This code will always be executed.”);

}

In this example, the code in the finally block will always be executed, regardless of whether an exception is thrown or not.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Inheritance
Certified Front-End Web Developer

Get industry recognized certification – Contact us

keyboard_arrow_up
Open chat
Need help?
Hello 👋
Can we help you?