• Post Reply Bookmark Topic Watch Topic
  • New Topic

throw execption in try -catch  RSS feed

 
varun bihani
Ranch Hand
Posts: 96
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can we throw user defined exception in try catch block ??

sth like:
try {
System.out.println("Hello " + args[0]);
}
catch (ArrayIndexOutOfBoundsException e) {
throw new Exception (" Error.");
}

Is it possible ?
 
mohit bahl
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes it is possible.

cheers!
 
Sanjaya Sugiarto
Ranch Hand
Posts: 229
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, it's ok. But you should understand the effect. You hand-over the exceptions to others and it would be like a snow ball. From the design point-of-view, it's ok if you throw the exception in try-catch block to your own exception class, not to general Exception.
 
Burkhard Hassel
Ranch Hand
Posts: 1274
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

Yes, you can do that. But when you rethrow a checked exception you either have to declare in the method signature that the methods will throw this Exception.
Or you have to catch it back again, looks really ugly:

Compiles and prints out
start
main ready
java.lang.ArrayIndexOutOfBoundsException: 0
at Main.main(Main.java:5)




Yours,
Bu.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!