Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

try..catch flow???

 
Sagar Sharma
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
when i try to compile the following code i recieve errors in the lines marked with **. The error says that "Statement not reached".
Is it true that i cannot have any line of code in the "if" blocks after the respective exceptions are thrown. i.e. is it true that "throw" should be the last statement of the block.
Please clear this doubt....
Thanks

import java.io.*;
import java.net.*;
class temp48{
public static void main(String args[]){

try{
String a=null;
String b=null;
if (a==null){
throw new MalformedURLException();
** System.out.println("bypass exception 1");
}
if (b==null){
throw new IOException();
** System.out.println("bypass exception 2");
}
}
catch(MalformedURLException me){
System.out.println("exception 1 caught");
return;
}
catch(IOException ie){
System.out.println("exception 2 caught");
return;
}
finally{
System.out.println("in finally()");
}
System.out.println("out of try block");
}
}
------------------
 
bill bozeman
Ranch Hand
Posts: 1070
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Haven't run across this problem before, but it would seem correct that you can't have anything after the throw statement. Once you throw that exception, it is going to jump to the catch block if you have one, so anything after the throw statement would never get executed. The compiler is telling you that because it thinks you made an error, and this code should be outside of the block. This is just my thought, but it seems like that is what the compiler is doing.
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3760
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are absolutely correct. Once the exception is thrown the control is out of the try block so the remaining statements ( of that block) are never reached. And that's what the compiler cribs about!
-Paul.

------------------
Get Certified, Guaranteed!
(Now Revised for the new Pattern)
www.enthuware.com/jqplus
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic