Monday, 3 August 2015

Throw before return statement



  • The following code gives compilation error as return is unreachable when the throw is not handled.


public class TestThrow {
public static void main(String[] args) throws Exception {
throw new Exception();
return; //Unreacheble code
}
}


  • The following code is alright and the return is reachable with no compilation error as throw is handled.

public class TestThrow {
public static void main(String[] args) {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return; // Now it's alright
}
}

No comments:

Post a Comment