0

My problem is I cannot make the inner catch throw an exception. Here I want ex to be thrown to the outer catch.

Runnable(){ public void run(){ try{ try{ }catch(Exception ex){ System.out.println("Inner"); throw ex; //I get an error here } }catch(Exception e){ System.out.println("Outer"); }} 

Error message: Unreported Exception must be caught, declared to be thrown

3
  • please post more info for your example, its just template Commented Sep 13, 2013 at 11:11
  • 1
    Is that all of the code? What you've posted should not produce an uncaught Exception error. Commented Sep 13, 2013 at 11:13
  • Both e and ex are of type Exception. No specializations.. Commented Sep 13, 2013 at 11:14

3 Answers 3

3

Put the block in a function .....

private void myFunction() throws Exception { try{ }catch(Exception ex){ System.out.println("Inner"); throw ex; //I get an error here } } 

Then call it from your code block

Runnable(){ public void run(){ try{ myFunction(); }catch(Exception e){ System.out.println("Outer"); }} 
Sign up to request clarification or add additional context in comments.

Comments

2

This seems to function just fine. Making nested try-catch blocks is considered bad practice.

public class Test implements Runnable { public void run() { try { try { throw new IOException("bad"); //throw something here } catch (Exception ex) { System.out.println("Inner"); throw ex; } finally { } } catch (Exception e) { System.out.println("Outer"); } } public static void main(String[] args) { new Test().run(); } } // PRINTS: // Inner // Outer 

Comments

0

try this.

Callable(){ public void call(){ try{ try{ }catch(Exception ex){ System.out.println("Inner"); throw ex; //I get an error here } }catch(Exception e){ System.out.println("Outer"); }} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.