Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Hari mylavar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Java Experts - Could you help me understand why the line after the catch block is executed. My understanding is after the exception - the flow goes to the catch block and does not execute beyond unless there is a finally block. Correct my understanding. Thank you -

public class NoExceptionHandling{
public static void main(String[] args){
int x=2, y=4, z=0;
try{
y=x/z; // division by 0
System.out.println("This line is not executed because of the exception");
}// end try
catch (Exception e){
System.out.println("Exception!");
}//end of catch block
System.out.println("Here we print the value of x/z = " + y); // I expected that this line will not be executed. See the output
}// end main method
}// end of class NoExceptionHandling
-------------------------------------------------------------
C:\ForAni\Java>java NoExceptionHandling
Exception!
Here we print the value of x/z = 4
 
jittu goud
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
welcome to javaranch could you please embed your code in [CODE] tags ....
 
jittu goud
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
the whole point of try catch is to recover your program from the known errors/exception.... in a program with out try catch ...it would probably crash....

so if exception occours in try block ...the code with in the try block after the exception is skipped....and the relavant action is taken in cathe...but the rest of the program should work normally....
 
Hari mylavar
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Jittu.

Note: I will use the code tag next time when I post. Thank you. -Hari
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic