RuntimeException이란?
프로그램 실행시 발생되는 예외들,
대표적인 RuntimeException의 후손들
- IndexoutOfBoundsException : 적절하지 않은 인덱스를 가지고 접근시 발생되는 예외
- NullPointerException : 참조변수가 null로 초기화 된 상태에서 변수나 메소드에 접근할 시 생기는 예외
- ClassCastException : 허용할 수 없는 형변환이 일어날 때 생기는 예외
- ArthmeticException : 0으로 무언가를 나누려할 때 생기는 예외
- NegativeArraySizeException : 배열의 크기를 음수로 넣으면 생기는 예외
예외 처리하는 방법!
1. try - cat 문을 사용
mathod01을 따로 만들어서 주석처럼 사용하면 된다.
public void method01() {
int n1,n2;
System.out.println("정수1 : ");
n1 = sc.nextInt();
System.out.println("정수2 : ");
n2 = sc.nextInt();
try { //try 중괄호 안에는 오류가 날만한 곳을 감시한다는 느낌이다
System.out.println("나누기 결과 : "+n1/n2);
} catch(ArithmeticException e) { //catch 안에는 오류가 날만한 예외를 적어준다.
System.out.println("0으로는 못나눠"); //catch안에 적은 예외가 발생할 경우 출력
e.printStackTrace(); //강제로 오류난 이력을 보고자 하면 쓴다
}
System.out.println("프로그램 종료");
}
또 try - catch 문은 catch를 여러번 사용할 수 있다.
public void method02() {
int s = sc.nextInt();
int[] arr = new int[s];
try {
System.out.println("100번 째 인덱스 값 : " + arr[100]);
} catch(IndexOutOfBoundsException i) {
System.out.println("부적절한 인덱스로 접근했습니다.");
} catch(NegativeArraySizeException n) {//catch를 두 번 사용한 모습.
System.out.println("음수로 배열의 크기를 지정할 수 없습니다.");
}
System.out.println("프로그램을 종료합니다");
}
try - catch의 모든 구문이 끝났을 때 사용하는 finally 도 있다.
코드의 일부분이다.
Scanner sc = new Scanner(System.in);
try {
int num = sc.nextInt();
}catch(ArithmeticException e) {
e.printStackTrace();
}
//finally try-catch의 결과와 상관없이 try-catch의 모든 과정이 끝났을 때 무조건 실행하는 구문
finally {
sc.close(); //열었던 스캐너 종료
}
2. throws 사용
throws는 한줄요약하면 에러 떠넘기기다.
에러가 발생할 경우 자기를 호출한 상위클래스로 에러를 던져버린다 라고 생각하면 편하다
또 반드시 예외처리를 해줘야하는 목록이 있다. IOStream의 IOException이 그 예다.
지금은 정리하지 않았지만 나중에 정리할 예정이다. 지금은 Scanner의 가볍고 빠른버젼이라고 보면 된다.
public void method03() throws IOException{ //예외처리 떠넘기기
/*
* CheckedException : 반드시 예외처리를 해야하는 예외들
* 조건문을 미리 제시할 수 없음( 예측이 불가한 곳에서 문제가 발생하기 때문에 예외처리가 필수다.
* 외부 매개체와 입출력이 일어날 때 발생된다.
* ex) Scanner, InputStreamReader
*/
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int a = Integer.parseInt(br.readLine()); //int 형 출력
double b= Double.parseDouble(br.readLine());
System.out.println(str);
System.out.println(a+b);
}
public void method04() throws IOException{
method05(); //05에서 발생된 에러가 호출한 곳으로 넘어왔다.
}
public void method05() throws IOException{
method06(); //06에서 발생된 에러가 호출한 곳으로 넘어왔다.
}
public void method06() throws IOException{
throw new IOException();
}
'JAVA 정리노트' 카테고리의 다른 글
JAVA I/O, stream에 대하여 (0) | 2024.02.02 |
---|---|
JAVA의 기본 API (2) | 2024.01.31 |
JAVA 추상메소드,클래스와 인터페이스 (0) | 2024.01.29 |
JAVA 의 다형성 (0) | 2024.01.24 |
JAVA 상속 (0) | 2024.01.23 |