Ticker

6/recent/ticker-posts

Documentation on Try-Catch in Java

Documentation on Try-Catch in Java

1. What is an Exception in Java?
An exception in Java is an event that disrupts the normal flow of a program's execution. It occurs when the program encounters an unexpected situation or error during runtime. Java exceptions are represented by objects, and they are used to handle abnormal conditions and provide a mechanism for error handling in Java programs.

2. Try-Catch Block
The try-catch block is used to handle exceptions in Java. The code that might throw an exception is placed within the try block, and the handling logic is specified in the corresponding catch block.

3. Syntax:

java
try {
// Code that may cause an exception
} catch (ExceptionType1 ex1) {
// Exception handling code for ExceptionType1
} catch (ExceptionType2 ex2) {
// Exception handling code for ExceptionType2
} finally {
// Optional 'finally' block for cleanup tasks
}

4. Explanation:

  • try: The try block encloses the code that may generate an exception. If any exception occurs within this block, the control is transferred to the corresponding catch block.

  • catch: Each catch block specifies the exception type it can handle. If an exception of the specified type (or its subclass) is thrown within the try block, the corresponding catch block is executed to handle the exception.

  • finally (optional): The finally block, if present, is executed regardless of whether an exception occurred or not. It is typically used to release resources or perform cleanup tasks that must be executed regardless of an exception's occurrence.

5. Example:

java
public class TryCatchExample {
public static void main(String[] args) {
try {
int num1 = 10;
int num2 = 0;
int result = num1 / num2; // This line will cause an ArithmeticException
System.out.println("Result: " + result); // This line won't be executed
} catch (ArithmeticException ex) {
System.out.println("Error: Cannot divide by zero!");
} finally {
System.out.println("Cleanup tasks or resource release can be done here.");
}
}
}

6. Output:


Error: Cannot divide by zero!
Cleanup tasks or resource release can be done here.

In the example above, the code attempts to divide num1 by num2, where num2 is 0. This causes an ArithmeticException to be thrown. The exception is caught in the catch block, and the appropriate error message is displayed. The finally block is executed afterward, regardless of the exception, allowing for cleanup tasks to be performed.

Remember to use specific exception types whenever possible and handle exceptions gracefully to make your Java programs more robust and user-friendly.

Post a Comment

0 Comments