Java Try Block Without Catch or Finally

#Interview-134: Java: Can we have a catch block without a try block, or a try block without a catch block? In Java, a catch block cannot exist without a try block – that is simply not allowed. The catch block is meant to handle exceptions thrown from the corresponding try, so without try, it has no purpose and won’t even compile. Now coming to the second part - can we have a try block without a catch? Yes, we can, but only if we use a finally block. So the valid combinations in Java are: 1. try + catch 2. try + catch + finally 3. try + finally 4.Just try alone (not allowed) Example of valid try without catch: try { int data = 10 / 0; } finally { System.out.println("This will always execute"); } Even though an exception occurs, the finally block will still execute. So - a catch block must always follow a try, but a try block can exist without a catch only if it is followed by a finally block. #interviewprep #interview #testing #qajobs #jobs #jobsearch #jobseekers #hiring #hiringnow #lookingforjob #manualtesting #testautomation #bdd #cucumber #testng #etltesting #performance #apitesting #softwaretesting #manualtester #qatester

To view or add a comment, sign in

Explore content categories