can we have try block without catch or finally block in java

‘try’ block without either a ‘catch’ block or a ‘finally’ block is not allowed in java.The main purpose of a ‘try’ block is to wrap code that might throw an exception, and it must be followed by either a ‘catch’ block to handle exceptions ‘finally’ block to execute code after the ‘try’ block regardless of whether an exception as thrown, or both.

can we have try block without catch or finally block in java

What is try block?

A ‘try’ block in java is construct used to wrap a section of code that might throw an exception.Its primary purpose is to define a scope where exceptions can be caught and handled, allowing the program to continue executing or terminating gracefully.’try’ block must be followed by at least one ‘catch’ block or a’finally’ block or both.

What is catch block?

A ‘catch’ block in java is used to handle exceptions that occur in the associated ‘try’ block.when an exception is thrown in the ‘try’ block,the runtime system looks for a corresponding ‘catch’ block that can handle that type of exception.

what is Finally block?

A finally block in java is used to execute code after a ‘try’ block and its corresponding ‘catch’ block, regardless of whether an exception was thrown or caught.
The finally ‘finally’ block is typically used for cleanup activities such as closing files, releasing  resources and other termination procedures that must happen even if an error occurs.

syntax:

1.Try with catch:

try{
}catch (ExceptionType1 e1){
}catch (ExceptionType2 e2){
}

2.Try with Finally:

try{
}finally{
}

3.Try with catch and finally:

try{
} catch (ExceptionType e){
} finally{
}

 

Example without catch or finally:

try{
    int result=10/0;
}

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top