简体   繁体   English

抛出线程陷阱

[英]Throw within a Catch in threads

My problem is I cannot make the inner catch throw an exception. 我的问题是我无法使内部捕获异常。 Here I want ex to be thrown to the outer catch. 在这里,我希望将ex扔到外面。

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 错误消息:必须捕获未报告的异常,声明为抛出

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");
}}

This seems to function just fine. 这似乎很好用。 Making nested try-catch blocks is considered bad practice. 制作嵌套的try-catch块被认为是不好的做法。

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

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");
}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM