Programing

Java에서 동일한 catch 블록에서 두 가지 예외를 잡을 수 있습니까?

crosscheck 2020. 8. 5. 07:49
반응형

Java에서 동일한 catch 블록에서 두 가지 예외를 잡을 수 있습니까? [복제]


이 질문에는 이미 답변이 있습니다.

동일한 처리 논리가 필요하므로 두 가지 예외를 포착해야합니다. 나는 다음과 같은 것을하고 싶다 :

catch (Exception e, ExtendsRuntimeException re) {
    // common logic to handle both exceptions
}

각 catch 블록에서 처리기 코드가 중복되는 것을 피할 수 있습니까?


자바 7 이상

Java 7부터 다중 예외 catch 가 지원됩니다.

구문은 다음과 같습니다.

try {
     // stuff
} catch (Exception1 | Exception2 ex) {
     // Handle both exceptions
}

정적 유형은 ex나열된 예외 중에서 가장 특수화 된 공통 상위 유형입니다. ex캐치에서 다시 던지면 나열된 예외 중 하나만 throw 될 수 있음을 컴파일러가 알고 있는 멋진 기능이 있습니다.


자바 6 및 이전

Java 7 이전에는이 ​​문제를 처리 할 수있는 방법이 있었지만 우아하지 않고 제한이있는 경향이 있습니다.

접근법 # 1

try {
     // stuff
} catch (Exception1 ex) {
     handleException(ex);
} catch (Exception2 ex) {
     handleException(ex);
}

public void handleException(SuperException ex) {
     // handle exception here
}

예외 처리기가 앞에 선언 된 로컬 변수에 액세스해야하는 경우 혼란스러워집니다 try. 그리고 핸들러 메소드가 예외를 다시 발생시켜야하는 경우 (그리고 점검되는 경우) 서명에 심각한 문제가 발생합니다. 특히 handleExceptionthrowing SuperException... 으로 선언해야합니다 . 이는 잠재적으로 둘러싸는 메소드의 서명을 변경해야한다는 의미입니다.

접근법 # 2

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     } else {
         throw ex;
     }
}

다시 한 번 서명에 문제가있을 수 있습니다.

접근법 # 3

try {
     // stuff
} catch (SuperException ex) {
     if (ex instanceof Exception1 || ex instanceof Exception2) {
         // handle exception
     }
}

If you leave out the else part (e.g. because there are no other subtypes of SuperException at the moment) the code becomes more fragile. If the exception hierarchy is reorganized, this handler without an else may end up silently eating exceptions!


Java <= 6.x just allows you to catch one exception for each catch block:

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Documentation:

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

For Java 7 you can have multiple Exception caught on one catch block:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Documentation:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html


If you aren't on java 7, you can extract your exception handling to a method - that way you can at least minimize duplication

try {
   // try something
}
catch(ExtendsRuntimeException e) { handleError(e); }
catch(Exception e) { handleError(e); }

For Java < 7 you can use if-else along with Exception:

try {
    // common logic to handle both exceptions
} catch (Exception ex) {
    if (ex instanceof Exception1 || ex instanceof Exception2) {

    }
    else {
        throw ex;
        // or if you don't want to have to declare Exception use
        // throw new RuntimeException(ex);
    }
}

Edited and replaced Throwable with Exception.


Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:

 try {
  // some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}

But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.

try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
   throw e;
}

So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.


http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html covers catching multiple exceptions in the same block.

 try {
     // your code
} catch (Exception1 | Exception2 ex) {
     // Handle 2 exceptions in Java 7
}

I'm making study cards, and this thread was helpful, just wanted to put in my two cents.

참고URL : https://stackoverflow.com/questions/11211286/is-it-possible-in-java-to-catch-two-exceptions-in-the-same-catch-block

반응형