Exception Handling Example in Java

September 5, 2023 by
Exception Handling Example in Java
Hamed Mohammadi
| No comments yet

Here is an example of exception handling in Java:

public class ExceptionDemo {

public static void main(String[] args) {
try {
// Code that may throw an exception
int data = 100 / 0;
} catch (ArithmeticException e) {
// Handle the exception
System.out.println("Division by zero error");
} finally {
// This block will always be executed, even if an exception is thrown
System.out.println("This code will always be executed");
}
}

}

In this example, we are trying to divide 100 by 0. This will cause an ArithmeticException to be thrown. The try block contains the code that may throw an exception. The catch block handles the exception by printing an error message. The finally block is always executed, even if an exception is thrown.

Here is another example of exception handling in Java:

public class ExceptionDemo2 {

public static void main(String[] args) throws IOException {
try {
// Code that may throw an exception
FileInputStream fis = new FileInputStream("myfile.txt");
} catch (IOException e) {
// Handle the exception
System.out.println("File not found");
throw e;
}
}

}

In this example, we are trying to open a file that does not exist. This will cause an IOException to be thrown. The try block contains the code that may throw an exception. The catch block handles the exception by printing an error message and then re-throwing the exception. This allows the caller of the main() method to handle the exception.

in Java
Exception Handling Example in Java
Hamed Mohammadi September 5, 2023
Share this post
Tags
Archive
Sign in to leave a comment