can we have try without catch block in java
Yes, you can have a try
block without a corresponding catch
block, but it must be followed by either a catch
block or a finally
block. The finally
block, if used, will always be executed, regardless of whether an exception is thrown or not. This is useful for cleanup operations, even if no exception occurs.
Here’s an example demonstrating a try
block without a catch
block, followed by a finally
block:
/*
* Author: Zameer Ali Mohil
* */
public class TryWithoutCatchExample {
public static void main(String[] args) {
try {
// Code that might cause an exception
int result = 10 / 0; // This will throw an ArithmeticException
System.out.println("Result: " + result); // This line will not be executed
} finally {
// Cleanup operations or code that always needs to be executed
System.out.println("Finally block executed.");
}
}
}
In this example, the try
block contains code that attempts to perform an illegal operation (dividing by zero), which results in an ArithmeticException
. There is no catch
block to handle this specific exception. However, the finally
block will still be executed after the try
block, allowing you to perform cleanup operations or any necessary tasks.
When you run the above code, it will throw an ArithmeticException
and execute the finally
block, producing the following output:
Finally block executed.
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TryWithoutCatchExample.main(TryWithoutCatchExample.java:6)
As you can see, the finally
block is always executed, providing a way to ensure specific actions are taken, even in the presence of exceptions.