【问题标题】:How to catch Exceptions occured in Catch block in Java如何在 Java 中捕获 Catch 块中发生的异常
【发布时间】:2024-04-24 12:10:01
【问题描述】:

我需要处理 Java 中的 Catch 块代码引发的异常

【问题讨论】:

  • 然后在 catch 块中编写代码。

标签: java exception try-catch


【解决方案1】:

我建议您调用另一个方法,而不是级联 try/catch(就像在大多数其他答案中一样),执行所需的操作。通过这种方式,您的代码将更易于维护
在这种方法中,放置一个 try/catch 块来保护代码。

例子:

public int classicMethodInCaseOfException(int exampleParam) {
    try {
        // TODO
    }
    catch(Exception e)
    {
        methodInCaseOfException();
    }
}


public int methodInCaseOfException()
{
    try {
        // TODO
    }
    catch(Exception e)
    {
        //TODO
    }
}

【讨论】:

    【解决方案2】:

    像在通常的 try/catch 情况下那样做:

    try{
        throw new Exception();
    }catch(Exception e1){
        try{
            throw new Exception();
        }catch(Exception e2){
        //do something
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以在主 catch 块中添加新的 try catch 块。

      try
            {
               int b=10/0;
            }catch(ArithmeticException e)
            {
               System.out.println("ArithmeticException occurred");
               try
               {
               int c=20/0;
               }catch(ArithmeticException e1)
               {
                  System.out.println("Another ArithmeticException occurred");
               }
            }
      

      【讨论】:

        【解决方案4】:

        我认为最干净的方法是创建捕获异常发生在其主体中的方法。但是,它可能在很大程度上取决于您正在处理的代码的情况和类型。

        您要询问的一个示例是关闭在try-catch-finally 块中打开的Stream。例如:

        package a;
        
        import java.io.BufferedOutputStream;
        import java.io.FileNotFoundException;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.OutputStream;
        
        public class Main {
        
            public static void main(String[] args) {
                OutputStream out = null;
                try {
                    out = new BufferedOutputStream(new FileOutputStream("temp.txt"));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    //TODO: Log the exception and handle it, 
                    //          for example show a message to the user
                } finally {
                    //out.close(); //Second level exception is 
                                   //  occurring in closing the
                                   //  Stream. Move it to a new method:
                    closeOutPutStreamResource(out); 
                }
            }
        
            private static void closeOutPutStreamResource(OutputStream out){
                try {
                    out.close();
                } catch (IOException e) {
                    // TODO: log the exception and ignore 
                    //          if it's not important
                    // OR
                    // Throw an instance of RuntimeException 
                    //      or one of it's subclasses
                    //      which doesn't make you to catch it
                    //      using a try-catch block (unchecked)
                    throw new CloseOutPutStreamException(e);
                }
            }
        }
        
        class CloseOutPutStreamException extends RuntimeException{
        
            public CloseOutPutStreamException() {
                super();
            }
        
            public CloseOutPutStreamException(String message, Throwable cause,
                    boolean enableSuppression, boolean writableStackTrace) {
                super(message, cause, enableSuppression, writableStackTrace);
            }
        
            public CloseOutPutStreamException(String message, Throwable cause) {
                super(message, cause);
            }
        
            public CloseOutPutStreamException(String message) {
                super(message);
            }
        
            public CloseOutPutStreamException(Throwable cause) {
                super(cause);
            }
        }
        

        这里我说明了第二级异常发生在finally块中的情况,但同样适用于catch块中发生的异常。

        在我看来,closeOutPutStreamResource 之类的编写方法很有用,因为它们打包了一个样板代码来处理非常常见的异常,并且它们使您的代码更加优雅。

        您也可以选择catch 并将异常记录到closeOutPutStreamResourcethrow 到程序的其他层。但是将这些不重要的已检查异常包装到RuntimeException 中而不需要捕获会更优雅。

        希望这会有所帮助。

        【讨论】:

          【解决方案5】:

          您可以在方法或块中的任何位置使用try catch块,因此您也可以在catch块中编写try catch。

          try {
          
          // master try
          
          }catch(Exception e){
          // master catch
          
          try {
          // child try in master catch
          
          }catch(Exception e1){
          // child catch in master catch
          
          }
          }//master catch
          

          【讨论】:

            【解决方案6】:

            例如,“处理”异常:

            try 
            {
             // try do something
            } 
            catch (Exception e) 
            {
                System.out.println("Caught Exception: " + e.getMessage());
                //Do some more
            }
            

            更多信息见:见:https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

            但是,如果您想在 try catch 中添加另一个 catch,您可以执行以下操作:

             try 
                 {
                       //Do something
                 } 
                 catch (IOException e) 
                 {
                        System.out.println("Caught IOException: " + e.getMessage());
            
                        try
                        {
                             // Try something else
                        }
                        catch ( Exception e1 )
                        {
                            System.out.println("Caught Another exception: " + e1.getMessage());                     
                        }
                 } 
            

            小心嵌套的 try/catch,当你的 try catch 变得复杂/大时,考虑将其拆分为自己的方法。例如:

            try {
                // do something here
            }
            catch(IOException e)
            {
                System.out.println("Caught IOException: " + e.getMessage());
                foo();
            }
            
            private void foo()
            {
                try {
                    // do something here (when we have the IO exception)
                }
                catch(Exception e)
                {
                    System.out.println("Caught another exception: " + e.getMessage());
                }
            }
            

            【讨论】:

              【解决方案7】:

              正如此处所有答案所暗示的那样,当 catch 块引发异常时,不必有嵌套的 try-catch 块。您可以使用 try-catch 将调用方方法括起来以处理该异常。

              【讨论】:

                最近更新 更多