Exception handling - Java

amit dutt

Broken In
here are 2 versions of same program:

version 1:


package dutt;

class App{

static void demo(){
try{
throw new NullPointerException("generic");
}catch(NullPointerException q){
System.out.println("caught inside demo");
throw q;
}
}

public static void main(String args[]){
try{
demo();
}catch(NullPointerException q){
System.out.println("caught inside main: " +q);
}
}
}


version 2:


package dutt;

class App{

static void demo(){
try{
throw new Exception("generic");
}catch(Exception q){
System.out.println("caught inside demo");
throw q;
}
}

public static void main(String args[]){
try{
demo();
}catch(Exception q){
System.out.println("caught inside main: " +q);
}
}
}


the only difference is I had used generic Exception class for version2 of program. while the version1 compiles without error, i get error in the version2: [Unhandlled exception type Exception]. i couldn't understand the reason. please help..

IDE used: Eclipse
 

Prime_Coder

I'm a Wannabe Hacker
U got the error in the second version of this program, because of the statement:
This statement is out of place.

Since 2nd version uses Exception class, you need to either put that statement in next try catch block (means u write nested blocks, in this case) OR Add a "throws" statement to the demo() signature just like:

static void demo() throws Exception
This approach requires any method that calls demo() to provide exception handling for demo()
 
Top Bottom