throw의 기초 이해.
package ch08exception;
public class MyExeption03 {
public static void main(String[] args) {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
try {
String xx = "aa";
first(xx);
}catch (ArithmeticException ex){//예외처리 떠넘기기. third의 예외를 main에게 떠넘기
System.out.println("0으로 나누지 마세요.");
}catch (NumberFormatException ex){
System.out.println("올바른 숫자 형식이 아닙니다.");
}catch (Exception ex){
System.out.println("기타 나머지 예외 발생.");
ex.printStackTrace();
}
}
private static void first(String xx) throws ArithmeticException, NumberFormatException {
int x = Integer.parseInt(xx); //파싱하다. 문자열을 숫자로 바꿈.
second();
}
private static void second() throws ArithmeticException {
third();
}
private static void third() throws ArithmeticException{ //상위스택에 예외처리 떠넘기기.
int i = 1, j = 0;
System.out.println(i / j);
}
}
"Thread"와 "예외처리를 꼭 해야하는 메서드"
- 꼭 예외처리를 해야하는 메소드가 있다.
- e.g. sleep() 메서드가 그 예이다.
- main 메서드가 실행되는 것은 하나의 논리적 단위인 Thread에서 실행되며, 이 쓰레드는 Java 애플리케이션이 시작될 때 생성된다. 이를 "main thread"라고 부른다.
- 꼭 예외처리를 해야하는 메소드가 있다.
throws 키워드
- 예외 처리를 상위 스택에게 떠 넘기기 위한 키워드
- 반환타입 메소드이름() throws Exception
- 사용자 정의 예외를 발생시킬때 사용하는 키워드
- throw 사용 상위 스택에 넘겨줬다면 상위 스택에서 try catch를 사용해야함.
잘 알야둬야할 예외
- NumberFormatException 자주 사용된다.
- 빨리 찾는 팁은 For input String:을 확인하는 것이다.
- NumberFormatException 자주 사용된다.
'자바 > 자바 문법' 카테고리의 다른 글
참조 변수와 기본 자료형 변수 (0) | 2025.01.21 |
---|---|
중복 선언 오류 (3) | 2025.01.15 |
자바 try-catch (0) | 2025.01.14 |
컬렉션 Map의 값 여러 개 넣는 법. (0) | 2025.01.13 |
증감 연산자 팁 (0) | 2024.12.31 |