Forum     

Go Back   Digit Technology Discussion Forum > Software > Programming
Register FAQ Calendar Mark Forums Read

Programming The destination for developers - C, C++, Java, Python and the lot


Reply
 
LinkBack Thread Tools Display Modes
Old 25-09-2011, 12:35 AM   #1 (permalink)
Apprentice
 
Join Date: Apr 2007
Posts: 63
Default Exception handling - Java


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
__________________
Amit Dutt
amit dutt is offline   Reply With Quote
Advertisements. Register and be a member of the community to get rid of them.
Advertisement

Old 25-09-2011, 03:04 AM   #2 (permalink)
I'm a Wannabe Hacker
 
Prime_Coder's Avatar
 
Join Date: Apr 2011
Location: Oxford of D East!
Posts: 235
Default Re: Exception handling - Java

U got the error in the second version of this program, because of the statement:
Quote:
throw q;
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:

Quote:
static void demo() throws Exception
This approach requires any method that calls demo() to provide exception handling for demo()
Prime_Coder is offline   Reply With Quote
Reply

Bookmarks

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


 
Latest Threads
- by Charan
- by Sarath
- by clmlbx

Advertisement




All times are GMT +5.5. The time now is 12:35 AM.


Powered by vBulletin® Version 3.8.7
Copyright ©2000 - 2012, vBulletin Solutions, Inc.

Search Engine Optimization by vBSEO 3.3.2