- It is possible to have try block without catch block by using finally block
- Java supports try with finally block
- As we know finally block will always executes even there is an exception occurred in try block, Except System.exit() it will executes always.
- We can place logic like connections closing or cleaning data in finally.
Java Program to write try without catch block | try with finally block
- package exceptionsInterviewQuestions;
- public class TryWithoutCatch {
- public static void main(String[] args) {
- try {
- System.out.println("inside try block");
- } finally{
- System.out.println("inside finally block");
- }
- }
- }
Output:
- inside try block
- inside finally block
- Finally block executes Even though the method have return type and try block returns something
Java Program to write try with finally block and try block returns some value
- package exceptionsInterviewQuestions;
- public class TryWithFinally {
- public static int method(){
- try {
- System.out.println("inside try block");
- return 10;
- } finally{
- System.out.println("inside finally block");
- }
- }
- public static void main(String[] args) {
- System.out.println(method());
- }
- }
Output:
- inside try block
- inside finally block
- 10
What happens if exception raised in try block?
- Even though exception raised in try block finally block executes.
Bagikan
Can we have try without catch block in java
4/
5
Oleh
Kris Kimcil