Operating System

Tuesday, April 9, 2019

Can we have only try block in Java without catch/finally?

Leave a Comment

Question 
Yes
No

Explanation: try block should have at least catch or finally block with it

public class HelloWorld{

     public static void main(String []args){
        try{
            System.out.println(1/0);
            
        }
     }
}
Above code gives "'try' without 'catch', 'finally' or resource declarations error"
public class HelloWorld{
     public static void main(String []args){
        try{
            System.out.println(1/0);
        }catch(Exception e){
            System.out.println("catch");
        }
     }
}
Above code compiles properly

public class HelloWorld{
     public static void main(String []args){
        try{
            System.out.println("try");
        }finally{
            System.out.println("finally");
        }
     }
}
Above code compiles properly
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment