• Post Reply Bookmark Topic Watch Topic
  • New Topic

why the statements after throw statement will not be executed.  RSS feed

 
Malayathi Partha Saradhi
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{
void method(){
try{
throw new Exception();
System.out.println("hello java");
}
catch(Exception e){
}
 
Cooky Hex
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It goes to the 'Catch' immediately while finding exception, and then executes what's after the 'Catch' block.
[ December 12, 2007: Message edited by: Cooky Lovy ]
 
Aditya Karnad
Greenhorn
Posts: 16
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code you have posted will probably show an error like "code unreachable".

You only use throw when you want to specify a restriction to the application you're working on. For example, in an employee information manager, an employee cannot specify his dependents to be two spouses... Thats a restriction that you want your business logic to handle. Thats when you use throw. And anything after throw statement will not execute.
 
Jilesh Lakhani
Ranch Hand
Posts: 49
Java Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you say throw new Exception() the control goes to the Catch block where you can give your output message.

After your catch block is executed, the control goes to the next statement after your try and catch block, so now try executing the below block it would print the "hello java"

class A{

void method(){
try{
throw new Exception();
}catch(Exception e){
}
System.out.println("hello java");
}//end of method
} //end of Class A

try reading http://java.sun.com/docs/books/tutorial/essential/exceptions/throwing.html
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Some people complain that throw is a thinly disguised GOTO. That may help explain why it can jump over statements, and even jump back up the call stack.

Throw can be like GOTO in a bad way if you use it for normal program logic. It really should indicate an exceptional condition, one that is not expected in normal processing. In that light, I'd argue against the "business restriction" definition above unless we discover two spouses via a duplicate key error in a database. There is room for some debate about what is "business" and what is "exceptional", but for sure: don't use throw as an alternative to if-then-else.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!