try catch block in java with example
Certainly! In Java, the
try-catch block is used to handle exceptions. The
try block contains the code that might throw an exception, and the
catch block catches and handles the exception if it occurs. Here’s an example to demonstrate the usage of the
In this example:
tryblock contains the code that might throw exceptions (an
InputMismatchExceptionif a non-integer input is given and an
ArithmeticExceptionif the user inputs 0).
catchblocks handle specific exceptions. In this case, the program catches
InputMismatchExceptionseparately and provides specific error messages for each type of exception.
finallyblock is optional and is used for cleanup operations. In this example, it closes the
Scannerobject, ensuring that it is always closed, regardless of whether an exception occurred or not.
try-catch block structure allows the program to gracefully handle exceptions and provide meaningful error messages to the user, enhancing the user experience and preventing the program from crashing due to unexpected inputs.