What are the forms of writing try/catch blocks in Java?
sobes.tech AI
Answer from AI
In Java, the following forms of writing try/catch/finally blocks exist:
-
Basic
try-catchform: Handles exceptions that occur within thetryblock.try { // Code that may throw an exception } catch (ExceptionType e) { // Code to handle ExceptionType } -
Multiple
catchblocks: Allows handling different types of exceptions differently.catchblocks are executed from top to bottom, and the first one that matches or is a parent of the thrown exception will be handled.try { // Code that may throw different types of exceptions } catch (SpecificExceptionType1 e1) { // Handling first type of exception } catch (SpecificExceptionType2 e2) { // Handling second type of exception } catch (Exception e) { // Handling other types of exceptions (should be last if present) } -
Multi-catch (Java 7+): Allows handling multiple exception types in one
catchblock if the handling logic is the same. Exception types are separated by|.try { // Code that may throw ExceptionType1 or ExceptionType2 } catch (ExceptionType1 | ExceptionType2 e) { // Handling both exception types } -
finallyblock: Used to execute code that should run regardless of whether an exception occurred or not (e.g., resource cleanup). Thefinallyblock executes after thetryblock and all relevantcatchblocks.try { // Code that may throw an exception } catch (ExceptionType e) { // Handle exception } finally { // Code that always executes }There is also a combination of
try-finallywithout acatchblock if the exception is not handled locally but cleanup code is needed.try { // Code } finally { // Code that always executes } -
Try-with-resources (Java 7+): Automatically closes resources that implement
AutoCloseableorCloseable. Resources are declared in parentheses after thetrykeyword.try (ResourceType resource1 = new ResourceType(...); AnotherResourceType resource2 = new AnotherResourceType(...)) { // Code using resource1 and resource2 } catch (ExceptionType e) { // Handle exception } // Resources resource1 and resource2 are automatically closedThis form can be used with
catchand/orfinallyblocks.try (ResourceType resource = new ResourceType(...)) { // Code using resource } finally { // Code executed after automatic resource closing }