【问题标题】:Throw within a Catch in threads在线程中的 Catch 内抛出
【发布时间】:2013-09-18 01:17:41
【问题描述】:

我的问题是我不能让内部 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");
}}

错误信息:必须捕获未报告的异常,声明要抛出

【问题讨论】:

  • 请为您的示例发布更多信息,它只是模板
  • 这就是全部代码吗?您发布的内容不应产生未捕获的Exception 错误。
  • e 和 ex 都是异常类型。没有专业..

标签: java multithreading exception try-catch throw


【解决方案1】:

将块放入函数中.....

private void myFunction() throws Exception {

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

然后从你的代码块中调用它

Runnable(){

public void run(){
    try{
        myFunction();
    }catch(Exception e){
    System.out.println("Outer");
}}

【讨论】:

    【解决方案2】:

    这似乎运行得很好。制作嵌套的 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
    

    【讨论】:

      【解决方案3】:

      试试这个。

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

      【讨论】:

        猜你喜欢
        • 2012-09-21
        • 1970-01-01
        • 1970-01-01
        • 2018-11-18
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 2010-11-12
        • 1970-01-01
        相关资源
        最近更新 更多