동일한 catch 절에서 여러 Java 예외를 포착 할 수 있습니까?
Java에서는 다음과 같이하고 싶습니다.
try {
...
} catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();
}
...대신에:
try {
...
} catch (IllegalArgumentException e) {
someCode();
} catch (SecurityException e) {
someCode();
} catch (IllegalAccessException e) {
someCode();
} catch (NoSuchFieldException e) {
someCode();
}
이렇게 할 수있는 방법이 있습니까?
이것은 Java 7 이후 로 가능했습니다 . 다중 캐치 블록의 구문은 다음과 같습니다.
try {
...
} catch (IOException | SQLException ex) {
...
}
그러나 모든 예외가 동일한 클래스 계층에 속하면 해당 기본 예외 유형을 간단히 포착 할 수 있습니다.
또한 ExceptionB가 ExceptionA에서 직접 또는 간접적으로 상속 된 경우 동일한 블록에서 ExceptionA와 ExceptionB를 모두 catch 할 수 없습니다. 컴파일러는 다음과 같이 불평합니다.
Alternatives in a multi-catch statement cannot be related by subclassing
Alternative ExceptionB is a subclass of alternative ExceptionA
Java 7 이전은 아니지만 다음과 같이 할 것입니다.
Java 6 이하
try {
//.....
} catch (Exception exc) {
if (exc instanceof IllegalArgumentException || exc instanceof SecurityException ||
exc instanceof IllegalAccessException || exc instanceof NoSuchFieldException ) {
someCode();
} else if (exc instanceof RuntimeException) {
throw (RuntimeException) exc;
} else {
throw new RuntimeException(exc);
}
}
자바 7
try {
//.....
} catch ( IllegalArgumentException | SecurityException |
IllegalAccessException |NoSuchFieldException exc) {
someCode();
}
Java 7 내에서 다음과 같은 여러 catch 절을 정의 할 수 있습니다.
catch (IllegalArgumentException | SecurityException e)
{
...
}
아니요, 고객 당 하나씩.
모든 경우에 동일한 조치를 취하는 한 java.lang.Exception과 같은 수퍼 클래스를 포착 할 수 있습니다.
try {
// some code
} catch(Exception e) { //All exceptions are caught here as all are inheriting java.lang.Exception
e.printStackTrace();
}
But that might not be the best practice. You should only catch an exception when you have a strategy for actually handling it - and logging and rethrowing is not "handling it". If you don't have a corrective action, better to add it to the method signature and let it bubble up to someone that can handle the situation.
If there is a hierarchy of exceptions you can use the base class to catch all subclasses of exceptions. In the degenerate case you can catch all Java exceptions with:
try {
...
} catch (Exception e) {
someCode();
}
In a more common case if RepositoryException is the the base class and PathNotFoundException is a derived class then:
try {
...
} catch (RepositoryException re) {
someCode();
} catch (Exception e) {
someCode();
}
The above code will catch RepositoryException and PathNotFoundException for one kind of exception handling and all other exceptions are lumped together. Since Java 7, as per @OscarRyz's answer above:
try {
...
} catch( IOException | SQLException ex ) {
...
}
A cleaner (but less verbose, and perhaps not as preferred) alternative to user454322's answer on Java 6 (i.e., Android) would be to catch all Exception
s and re-throw RuntimeException
s. This wouldn't work if you're planning on catching other types of exceptions further up the stack (unless you also re-throw them), but will effectively catch all checked exceptions.
For instance:
try {
// CODE THAT THROWS EXCEPTION
} catch (Exception e) {
if (e instanceof RuntimeException) {
// this exception was not expected, so re-throw it
throw e;
} else {
// YOUR CODE FOR ALL CHECKED EXCEPTIONS
}
}
That being said, for verbosity, it might be best to set a boolean or some other variable and based on that execute some code after the try-catch block.
In pre-7 how about:
Boolean caught = true;
Exception e;
try {
...
caught = false;
} catch (TransformerException te) {
e = te;
} catch (SocketException se) {
e = se;
} catch (IOException ie) {
e = ie;
}
if (caught) {
someCode(); // You can reference Exception e here.
}
Catch the exception that happens to be a parent class in the exception hierarchy. This is of course, bad practice. In your case, the common parent exception happens to be the Exception class, and catching any exception that is an instance of Exception, is indeed bad practice - exceptions like NullPointerException are usually programming errors and should usually be resolved by checking for null values.
Yes. Here's the way using pipe( | ) separator,
try
{
.......
}
catch
{
catch(IllegalArgumentException | SecurityException | IllegalAccessException | NoSuchFieldException e)
}
For kotlin, it's not possible for now but they've considered to add it: Source
But for now, just a little trick:
try {
// code
} catch(ex:Exception) {
when(ex) {
is SomeException,
is AnotherException -> {
// handle
}
else -> throw ex
}
}
'Programing' 카테고리의 다른 글
Emacs와 Vim의 차이점 (0) | 2020.10.02 |
---|---|
HTML에서 ID와 이름 속성의 차이점 (0) | 2020.10.02 |
npm 스크립트에 명령 줄 인수 보내기 (0) | 2020.10.02 |
'SELECT'문의 'IF'-열 값에 따라 출력 값 선택 (0) | 2020.10.02 |
jQuery hasAttr checking to see if there is an attribute on an element [duplicate] (0) | 2020.10.02 |