예외클래스와 throws의 이해가 부족합니다.
-
게시물 수정 , 삭제는 로그인 필요
예외처리가 많이 헷갈리네요. 많이 고심해봤는데도 이해가 안되는것이 있어서
아무쪼록 자세하게 알려주시면 감사합니다...
1. catch 블럭은 메소드의 호출이 아니라 선언이나 정의에 가까운가요? e 처럼 왜 참조변수를 아무거나 넣어도 되는지 이해가 가질 않았습니다.
try {
Exception anything = new Exception("고의발생"); // 1. 예외 생성
throw anything; //
} catch (Exception e) {
System.out.println("에러메세지:" + e.getMessage());
e.printStackTrace();
}
이런 경우처럼 어떤 참조변수를 가지는 인스턴스가 발생하든지 catch 블록의 매개변수는 신경을 안쓰더라구요. 이는 catch블록은 클래스타입만을 판별하기 위한 '선언이나 정의'에 가까운 코드이기 때문인가요?
2. throw를 하면 return처럼 바로 프로그램이 종료되나요?
3. throws에 해당되는 예외클래스는 호출된 클래스에 예외를 전달한다는데 throws를 쓰지 않아 내부클래스에서 예외를 처리해야 하는 경우를 잘 모르겠습니다. throws 없이도 전달되는 것 같거든요.
class test {
class PreN extends NullPointerException {
public PreN() {
}
}
class PreA extends ArrayIndexOutOfBoundsException {
public PreA() {
}
}
void pretest() throws PreN { //N을 명시, A를 발생
throw new PreA();
}
}
public class practice {
public static void main(String[] args) {
test t = new test();
try{
t.pretest();
} catch (test.PreN q){
System.out.println("PreN에서 발생");
} catch (test.PreA u) {
System.out.println("PreA에서 발생");
}
}
}
가령 이렇게 다른 예외를 만들어서 throws에 명시한 예외가 아니라 다른 예외상황이 발생했는데도 practice 클래스에 예외가 전달되어 catch가 잡아냅니다.
[PreA에서 발생]이 나옵니다.
제가 코드를 잘못 짠건지, throws에 대해 잘못이해한건지 모르겠습니다.
throws를 쓰지 않아도 호출된 클래스에서 catch블록에 전달된다면 throws로 예외클래스를 명시하는 이유가 무엇인가요?
try {
Exception anything = new Exception("고의발생"); // 1. 예외 생성
throw anything; //
} catch (Exception e) {
System.out.println("에러메세지:" + e.getMessage());
e.printStackTrace();
}
class test {
class PreN extends NullPointerException {
public PreN() {
}
}
class PreA extends ArrayIndexOutOfBoundsException {
public PreA() {
}
}
void pretest() throws PreN { //N을 명시, A를 발생
throw new PreA();
}
}
public class practice {
public static void main(String[] args) {
test t = new test();
try{
t.pretest();
} catch (test.PreN q){
System.out.println("PreN에서 발생");
} catch (test.PreA u) {
System.out.println("PreA에서 발생");
}
}
}