Java 메서드 선언에서 throw를 사용하는 경우
그래서 저는 Java에서 예외 처리에 대한 기본적인 이해가 좋다고 생각했지만 최근에 약간의 혼란과 의심을주는 코드를 읽고있었습니다. 내가 여기서 다루고 싶은 가장 큰 의심은 사람이 다음과 같은 Java 메서드 선언을 언제 사용해야 하는가입니다.
public void method() throws SomeException
{
// method body here
}
유사한 게시물을 읽음으로써 throws 는 메서드 실행 중에 SomeException이 발생할 수 있다는 일종의 선언으로 사용됩니다 .
내 혼란은 다음과 같은 코드에서 비롯됩니다.
public void method() throws IOException
{
try
{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
이 예제에서 던지기 를 사용하려는 이유가 있습니까? IOException과 같은 기본적인 예외 처리를 수행하는 경우 단순히 try / catch 블록이 필요하며 그게 전부인 것 같습니다.
예외 유형을 포착하는 경우 다시 던지지 않는 한이를 던질 필요가 없습니다. 게시하는 예제에서 개발자는 둘 다가 아닌 둘 중 하나를 수행해야합니다.
일반적으로 예외에 대해 아무것도하지 않으려면 포착해서는 안됩니다.
당신이 할 수있는 가장 위험한 일은 예외를 잡아서 아무것도하지 않는 것입니다.
예외를 던지는 것이 적절한시기에 대한 좋은 논의는 여기에 있습니다.
메서드가 확인 된 예외를 throw하는 경우 메서드에 throws 절을 포함하기 만하면됩니다. 메서드가 런타임 예외를 throw하면 그렇게 할 필요가 없습니다.
확인 된 예외와 확인되지 않은 예외에 대한 배경 정보는 다음을 참조하십시오 . http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
메서드가 예외를 포착하고 내부적으로 처리하는 경우 (두 번째 예제에서와 같이) throws 절을 포함 할 필요가 없습니다.
당신이 본 코드는 이상적이지 않습니다. 다음 중 하나를 수행해야합니다.
예외를 잡아서 처리하십시오. 이 경우
throws
불필요합니다.제거
try/catch
; 이 경우 Exception은 호출 메서드에 의해 처리됩니다.예외를 포착하고, 가능하면 몇 가지 조치를 수행 한 다음 예외를 다시 발생시킵니다 (메시지뿐만 아니라)
당신 말이 맞아요, 그 예에서는 throws
불필요한 것입니다. 이전 구현에서 남겨졌을 가능성이 있습니다. 아마도 예외가 catch 블록에서 잡히지 않고 원래 던져졌을 것입니다.
제공 한 예제에서 메서드는 IOException을 throw하지 않으므로 선언이 잘못되었습니다 (그러나 유효 함). 내 생각 엔 원래 메서드가 IOException을 던졌지 만 예외를 처리하도록 업데이트되었지만 선언이 변경되지 않았습니다.
게시 한 코드가 잘못되었습니다. IOException을 처리하기 위해 특정 예외를 포착하지만 포착되지 않은 예외를 던지는 경우 예외가 발생해야합니다.
다음과 같은 것 :
public void method() throws Exception{
try{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}catch(IOException e){
System.out.println(e.getMessage());
}
}
또는
public void method(){
try{
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
}catch(IOException e){
System.out.println("Catching IOException");
System.out.println(e.getMessage());
}catch(Exception e){
System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
System.out.println(e.getMessage());
}
}
이것은 대답이 아니라 주석이지만 형식화 된 코드로 주석을 작성할 수 없으므로 여기에 주석이 있습니다.
있다고 가정하자
public static void main(String[] args) {
try {
// do nothing or throw a RuntimeException
throw new RuntimeException("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
출력은
test
Exception in thread "main" java.lang.RuntimeException: test
at MyClass.main(MyClass.java:10)
That method does not declare any "throws" Exceptions, but throws them! The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method. It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception
Now, if we have
public static void main(String[] args) throws Exception {
try {
throw new Exception("test");
} catch (Exception e) {
System.out.println(e.getMessage());
throw e;
}
}
We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.
참고URL : https://stackoverflow.com/questions/4392446/when-to-use-throws-in-a-java-method-declaration
'Nice programing' 카테고리의 다른 글
OPTIONS 프리 플라이트 요청을 건너 뛰는 방법은 무엇입니까? (0) | 2020.10.05 |
---|---|
만약 ' (0) | 2020.10.05 |
서블릿이 "HTTP 상태 404 요청한 리소스 (/ servlet)를 사용할 수 없습니다."를 반환합니다. (0) | 2020.10.05 |
경고 : 상수 :: Fixnum은 새 모델을 생성 할 때 더 이상 사용되지 않습니다. (0) | 2020.10.05 |
추상 클래스보다 특성을 사용하는 장점은 무엇입니까? (0) | 2020.10.05 |