📜  java try catch - Java (1)

📅  最后修改于: 2023-12-03 15:31:32.673000             🧑  作者: Mango

Java Try-Catch

In Java, exceptions can occur during program execution, and if not handled properly, they can lead to unexpected results. This is where the try-catch statement comes in handy. It allows us to catch and handle exceptions in a controlled manner.

Syntax
try {
    // code that may throw an exception
} catch (ExceptionType e) {
    // code to handle the exception
} finally {
    // optional code to be executed regardless of whether an exception was caught or not
}
  • The try block contains the code that may throw an exception.
  • The catch block contains the code to handle the exception.
  • The finally block contains code that will be executed regardless of whether an exception was caught or not. This block is optional.
Example
int x = 10, y = 0;
try {
    int z = x / y;
    System.out.println(z);
} catch (ArithmeticException e) {
    System.out.println("Error: " + e.getMessage());
} finally {
    System.out.println("The finally block has executed.");
}

In this example, we attempt to divide x by y, where y is 0. An ArithmeticException is thrown when attempting to divide an integer by 0. The catch block catches the exception and prints an error message. The finally block prints a message indicating that it has executed.

Multiple catch blocks

It is possible to have multiple catch blocks for the same try block, each catching a different type of exception. This allows for different error handling depending on the type of exception that is thrown.

try {
    // code that may throw an exception
} catch (ExceptionType1 e) {
    // code to handle exception type 1
} catch (ExceptionType2 e) {
    // code to handle exception type 2
}
Catching parent exceptions

It is also possible to catch parent exceptions and their subclass exceptions using the catch block. For example, if MyException is a subclass of Exception, we can catch both MyException and Exception using the following code:

try {
    // code that may throw an exception
} catch(MyException | Exception e) {
    // code to handle the exception
}
Conclusion

The try-catch statement is a powerful tool for handling exceptions in Java. It allows us to catch and handle exceptions in a controlled manner, preventing unexpected results and making our code more robust.