Nested try-catch blocks
Hello All,
If I have 2 nested try-catch blocks see below
try{
//....
//Some code
try{
//Code that throws an IOException
}catch(NumberFormatException nfe){
//Handle the NFE
}
}catch(Exception e){
//Handle the Exception
}
Now what happens if in the inner try-catch an IOException is thrown? Will it be ignored, or will it get thrown out to the outer one and be caught by that catch?
Thanks,
Matt
try it this way:-
try{
//....
//Some code
try{
//Code that throws an IOException
throw new java.io.IOException();
}catch(NumberFormatException nfe){
//Handle the NFE
System.out.println("caught in inner block");
}
}catch(Exception e){
//Handle the Exception
System.out.println("caught in outer block");
}
Thanks, should have just done this from the start, but here is the result...
The following code
public class Main {
public void execute(){
try{
try{
for(int i=0;i<100;i++){
System.out.println(i);
if(i==5){
throw new java.io.IOException();
}
}
}catch(NumberFormatException nfe){
System.out.println("caught in inner block");
}
}catch(Exception e){
//Handle the Exception
System.out.println("caught in outer block");
}
}
public static void main(String[] args) {
Main m = new Main();
m.execute();
}
}
GENERATES:
0
1
2
3
4
caught in outer block
Thanks,
Matt
It would be the same as writing...
public class Main {
public void execute(){
try{
for(int i=0;i<100;i++){
System.out.println(i);
if(i==5){
throw new java.io.IOException();
}
}
}catch(NumberFormatException nfe){
System.out.println("caught in first block");
}catch(Exception e){
//Handle the Exception
System.out.println("caught in second block");
}
}
public static void main(String[] args) {
Main m = new Main();
m.execute();
}
}
BTW If you want to catch an exception in the inner and outer block you can
try {
try {
try {
try {
throw new SocketException();
} catch (SocketException se) {
// caught here..
throw se;
}
} catch (IOException ioe) {
// and here..
throw ioe;
}
} catch (Exception e) {
// and here..
throw e;
}
} catch (Throwable t) {
// and here..
throw t;
}
Are there any benefits/issues to:
try
{
//something that might throw an exception
try
{
//do something else that might throw an exception
}
catch (Exception e)
{
//handler intended for the second action
}
}
catch (Exception e)
{
//handler intended for the first
}
Would the second be caught in both places? Is there a downside to doing this? Or would it be better to spend the time looking into all the different exceptions that could be caught here (there are quite a few!)?