Java에서 사용자 정의 예외를 작성하는 방법은 무엇입니까? [닫은]
Java에서 사용자 정의 예외를 작성하는 방법
점검 된 예외 를 정의하려면 의 서브 클래스 (또는 서브 클래스 계층)를 작성하십시오 java.lang.Exception
. 예를 들면 다음과 같습니다.
public class FooException extends Exception {
public FooException() { super(); }
public FooException(String message) { super(message); }
public FooException(String message, Throwable cause) { super(message, cause); }
public FooException(Throwable cause) { super(cause); }
}
이 예외를 던지거나 전파 할 수있는 메소드는 다음을 선언해야합니다.
public void calculate(int i) throws FooException, IOException;
...이 메소드를 호출하는 코드는이 예외를 처리하거나 전파해야합니다 (또는 둘 다).
try {
int i = 5;
myObject.calculate(5);
} catch(FooException ex) {
// Print error and terminate application.
ex.printStackTrace();
System.exit(1);
} catch(IOException ex) {
// Rethrow as FooException.
throw new FooException(ex);
}
위의 예에서 IOException
로 잡히고 다시 던져지는 것을 알 수 FooException
있습니다. 이것은 일반적으로 API를 구현할 때 예외를 캡슐화하는 데 사용되는 일반적인 기술입니다.
때로는 모든 메소드가 throws 절에 예외 구현을 선언하도록 강요하지 않는 상황이있을 수 있습니다. 이 경우 검사되지 않은 예외를 만들 수 있습니다 . 검사되지 않은 예외는 확장 java.lang.RuntimeException
되는 예외입니다 (자체 하위 클래스 임 java.lang.Exception
).
public class FooRuntimeException extends RuntimeException {
...
}
메소드는 FooRuntimeException
예외를 선언하지 않고 예외를 던지거나 전파 할 수 있습니다 . 예 :
public void calculate(int i) {
if (i < 0) {
throw new FooRuntimeException("i < 0: " + i);
}
}
검사되지 않은 예외는 일반적으로 프로그래머 오류를 표시하는 데 사용됩니다 (예 : 유효하지 않은 인수를 메소드에 전달하거나 배열 색인 경계를 위반하려는 시도).
이 java.lang.Throwable
클래스는 Java 내에서 발생할 수있는 모든 오류 및 예외의 근본입니다. java.lang.Exception
그리고의 java.lang.Error
서브 클래스입니다 Throwable
. 서브 클래스 Throwable
가 발생하거나 잡힐 수 있습니다. 그러나 일반적으로 Error
프로그래머가 처리 할 수없는 JVM 내부 오류 (예 :)를 나타내는 데 사용되므로 일반적으로 catch 또는 throw하는 것은 좋지 않습니다 OutOfMemoryError
. 마찬가지로을 잡는 것을 피해야합니다. Throwable
이 경우 Error
s 외에을 잡을 수도 있습니다 Exception
.
public class MyException extends Exception {
// special exception code goes here
}
그것을 다음과 같이 던져라 :
throw new MyException ("Something happened")
다음과 같이 잡기 :
catch (MyException e)
{
// something
}
확인 된 예외의 경우 :
public class MyCustomException extends Exception { }
Technically, anything that extends Throwable
can be an thrown, but exceptions are generally extensions of the Exception
class so that they're checked exceptions (except RuntimeException or classes based on it, which are not checked), as opposed to the other common type of throwable, Error
s which usually are not something designed to be gracefully handled beyond the JVM internals.
You can also make exceptions non-public, but then you can only use them in the package that defines them, as opposed to across packages.
As far as throwing/catching custom exceptions, it works just like the built-in ones - throw via
throw new MyCustomException()
and catch via
catch (MyCustomException e) { }
참고URL : https://stackoverflow.com/questions/1754315/how-to-create-custom-exceptions-in-java
'Programming' 카테고리의 다른 글
Google지도에 영향을주는 Twitter 부트 스트랩 CSS (0) | 2020.06.13 |
---|---|
지역 민감 해싱을 이해하는 방법? (0) | 2020.06.13 |
리스트 / 튜플 쌍을 두리스트 / 튜플로 풀기 (0) | 2020.06.13 |
쿼리 실행시 Sequelize가 콘솔에 SQL을 출력하지 못하게 하시겠습니까? (0) | 2020.06.13 |
긴 단어가 내 div를 깨는 것을 방지하는 방법은 무엇입니까? (0) | 2020.06.13 |