如何捕获Java中catch块中发生的异常

如何捕获Java中catch块中发生的异常,java,exception,try-catch,Java,Exception,Try Catch,我需要处理Java中Catch块代码引发的异常您可以在方法或块中的任何位置使用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 例如,要“

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

您可以在方法或块中的任何位置使用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
例如,要“处理”异常:

try 
{
 // try do something
} 
catch (Exception e) 
{
    System.out.println("Caught Exception: " + e.getMessage());
    //Do some more
}
更多信息请参阅:请参阅:

但是,如果您想在try 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());                     
            }
     } 

小心嵌套的尝试/catch,当您的catch 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());
    }
}

在通常的“尝试/抓住”情况下,按照您的做法:

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

您可以在主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");
         }
      }

我认为最干净的方法是创建一个方法,该方法捕获在其主体中发生的异常。但是,它可能非常依赖于您正在处理的情况和代码类型

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

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
这样的编写方法非常有用,因为它们打包了一个锅炉板代码,用于处理非常常见的异常,并且使代码更加优雅

您还可以选择
捕获
并将异常记录在
closeOutPutStreamResource
中,或者
将其抛出到程序的其他层。但是,将这个不重要的已检查异常包装到
RuntimeException
中,而不需要捕获,这将更加优雅


希望这会有所帮助。

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

例如:

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


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

当catch块抛出异常时,不必像这里的所有答案所建议的那样使用嵌套的try-catch块。您可以用try-catch封装调用方方法来处理该异常。

然后在catch块内编写代码。