try / catch vs 예외 발생
이 코드 문장은 동일합니까? 그들 사이에 차이점이 있습니까?
private void calculateArea() throws Exception {
....do something
}
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
그렇습니다. 큰 차이가 있습니다. 후자는 예외를 삼킨다 (확실히 보여줌). 첫 번째 예외는 전파됩니다. (나는 그것을 다시 showException
던지지 않는다고 가정한다 .)
따라서 첫 번째 메소드를 호출하고 "무언가 수행"이 실패하면 호출자가 예외를 처리해야합니다. 두 번째 메서드를 호출하고 실패 "무언가를"경우를 제외하고 호출자는 일반적으로 나쁜 일이 전혀 예외를 ... 볼 수 없습니다 showException
했다 진정으로 잘못 어떤 고정 된 예외를 처리, 일반적으로 확인했다 그 calculateArea
목적을 달성했다.
당신은 당신이없이 첫 번째 방법을 호출 할 수 있기 때문에, 이것을 말할 수 있습니다 중 하나를 잡기 Exception
자신 또는 귀하의 방법은 너무 그것을 던질 수 있음을 선언.
첫 번째 throws Exception
는 호출자가를 처리해야합니다 Exception
. 두 번째는 Exception
내부적으로 잡고 처리 하므로 호출자가 예외 처리를 수행 할 필요가 없습니다.
예. 선언하는 버전 throws Exception
은 예외를 처리하기 위해 호출 코드가 필요하지만 명시 적으로 예외를 처리하는 버전은 그렇지 않습니다.
즉, 간단히 :
performCalculation();
예외를 처리하는 부담을 호출자에게 옮기는 것
try {
performCalculation();
catch (Exception e) {
// handle exception
}
그렇습니다. 그들 사이에는 큰 차이가 있습니다. 첫 번째 코드 블록에서 예외를 호출 코드에 전달합니다. 두 번째 코드 블록에서는 직접 처리합니다. 올바른 방법은 전적으로 수행중인 작업에 따라 다릅니다. 어떤 경우에는 코드에서 예외를 처리하기를 원하지만 (예를 들어 파일을 찾지 못하고 작성하려는 경우), 다른 경우에는 호출 코드에서 예외를 처리하기를 원합니다 (파일을 찾을 수 없음) 새 것을 지정하거나 만들어야합니다).
일반적으로 말해서 일반적인 예외를 잡기를 원하지 않습니다. 대신에, FileNotFoundException
또는 IOException
다른 것을 의미 할 수 있기 때문에 특정 것을 잡기를 원할 것입니다.
throw를 사용할 수없는 특정 시나리오가 있습니다. try-catch를 사용해야합니다. "재정의 된 메소드는 상위 클래스가 던지는 것 이외의 추가 예외를 처리 할 수 없습니다"라는 규칙이 있습니다. try-catch를 사용하여 처리해야 할 추가 예외가있는 경우 이 코드 스 니펫을 고려하십시오. 간단한 기본 수업이 있습니다
package trycatchvsthrows;
public class Base {
public void show()
{
System.out.println("hello from base");
}
}
그리고 파생 클래스입니다.
package trycatchvsthrows;
public class Derived extends Base {
@Override
public void show() {
// TODO Auto-generated method stub
super.show();
Thread thread= new Thread();
thread.start();
try {
thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// thread.sleep(10);
// here we can not use public void show() throws InterruptedException
// not allowed
}
}
thread.sleep ()을 호출해야 할 때 try-catch를 사용해야하는데 여기서는 사용할 수 없습니다.
public void show() throws InterruptedException
재정의 된 메소드는 추가 예외를 throw 할 수 없기 때문입니다.
나는 "동일한"것으로 행동을 의미한다고 가정합니다.
함수의 동작은 다음에 의해 결정될 수 있습니다.
1) 반환 값
2) 예외 발생
3) 부작용 (즉, 힙, 파일 시스템 등의 변경)
In this case, the first method propagates any exception, while the second throws no checked exception, and swallows most of the unchecked exceptions as well, so the behavior IS different.
However, if you guarantee that "do something" never throws an exception, then the behavior would be identical (though the compiler will require the caller to handle the exception, in the first version)
--edit--
From the point of view of API design, the methods are completely different in their contract. Also, throwing class Exception is not recommended. Try throwing something more specific to allow the caller to handle the exception better.
If you threw an exception, the child method (which overrides this) should handle the exception
example:
class A{
public void myMethod() throws Exception{
//do something
}
}
A a=new A();
try{
a.myMethod();
}catch Exception(e){
//handle the exception
}
Many times you want the caller to handle the exception. Let's say you have the caller call a method which calls another method which calls another method, instead of having each method handle the exception, you can just handle it at the caller. Unless, you want to do something in one of the methods when that method fails.
The caller of this method will need to either catch this exception or declare it to be rethrown in it's method signature.
private void calculateArea() throws Exception {
// Do something
}
In the try-catch block example below. The caller of this method doesn't have to worry about handling the exception as it has already been taken care of.
private void calculateArea() {
try {
// Do something
} catch (Exception e) {
showException(e);
}
}
private void calculateArea() throws Exception {
....do something
}
This throws the exception,so the caller is responsible for handling that exception but if caller does not handle the exception then may be it will given to jvm which may result in abnormal termination of programe.
Whereas in second case:
private void calculateArea() {
try {
....do something
} catch (Exception e) {
showException(e);
}
}
Here the exception is handled by the callee,so there is no chance of abnormal termination of the program.
Try-catch is the recommended approach.
IMO,
Throws keyword mostly used with Checked exceptions to convince compiler but it does not guarantees normal termination of program.
Throws keyword delegate the responsibility of exception handling to
the caller(JVM or another method).Throws keyword is required for checked exceptions only ,for unchecked exceptions there is no use of throws keyword.
참고URL : https://stackoverflow.com/questions/3241571/try-catch-versus-throws-exception
'development' 카테고리의 다른 글
nodejs를 사용하여 기본 브라우저를 열고 특정 URL로 이동하는 방법 (0) | 2020.07.26 |
---|---|
캐럿 (^) 문자는 무엇을 의미합니까? (0) | 2020.07.26 |
C ++에서 유지 관리 가능하고 빠른 컴파일 타임 비트 마스크를 작성하는 방법 (0) | 2020.07.26 |
분당 100k 적중을 얻기 위해 nginx worker_process 조정 (0) | 2020.07.26 |
Thread.Sleep이 왜 그렇게 해로운가요? (0) | 2020.07.26 |