The catch
keyword in Java is used in a try-catch
block to handle exceptions that may be thrown during the execution of a program.
A try-catch
block has the following syntax:
try { // Code that may throw an exception } catch (ExceptionType exceptionVariable) { // Code to handle the exception }Sourc.www:elautturi.com
Here, the try
block contains the code that may throw an exception, and the catch
block contains the code that will be executed if an exception is thrown. The ExceptionType
parameter specifies the type of exception that the catch
block can handle, and the exceptionVariable
is a variable that will hold the exception object if an exception is thrown.
For example, consider the following code:
try { int x = 5 / 0; } catch (ArithmeticException e) { System.out.println("An arithmetic exception occurred: " + e.getMessage()); }
In this code, the try
block contains a division by zero operation, which will throw an ArithmeticException
. The catch
block will handle this exception and print a message to the console.
You can have multiple catch
blocks to handle different types of exceptions. For example:
try { // Code that may throw an exception } catch (ExceptionType1 exceptionVariable1) { // Code to handle ExceptionType1 } catch (ExceptionType2 exceptionVariable2) { // Code to handle ExceptionType2 }
It's important to note that the order of the catch
blocks matters. The exception will be caught by the first catch
block whose ExceptionType
is compatible with the exception that was thrown. If none of the catch
blocks can handle the exception, it will be propagated up to the calling method.