JAVA
33. 예외처리
NamGH
2023. 8. 8. 16:48
예외처리란?
실행 타임에 에러가 발생하면 에러 이벤트가 발생했다고하는데 이 이벤트를 Exception이라고 한다
예외가 발생한 메서드 내에서 직접 처리하는 try~catch문과
예외가 발생한 메서드 내에서 예외처리가 곤란한 경우 발생 예외를 자신을 호출한 메서드로 보내주는 방법인
throw로 예외 처리를 할 수 있다
예외 처리를 사용하는 이유
에러를 미연에 방지할수 있다
시스템의 안정성을 확보할수 있다
에러 이벤트 발생시 위치를 확인하고 적절한 대응을 할 수 있다
사용예시
try{
에러 감지하는 블록
에러가 발생할 가능성이 있는 코드
}catch(에러이벤트1 변수({
에러이벤트1이 발생했을시 이벤트가
넘어와 처리됨
}finally{
예외 처리 상관없이 무조건
처리해야하는 작업
}
class AA{
String name; //인스턴트 변수: 초기에 값이 붙을수 업음
int age;
}
public class Ex01_try_catch {
public static void main(String[] args) {
String name = null;
int age = 0;
AA a = new AA();
System.out.println(a.name);
System.out.println(a.age);
System.out.println(name);
System.out.println(age);
try { // try catch는 처음 발생한 에러만 처리한다 즉 한 변수의 에러만 잡아냄
int len = name.length();
System.out.println("len:" + len);// new java.lang.NullPointerException()
int b = 3 / 0; // ArithmeticException
}catch(Exception e) { // 모든 에러를 잡아줌
System.out.println(e);
System.out.println("Exception");
}finally { // 무조건 출력
System.out.println("finally 영역");
}
System.out.println("프로그램 종료");
System.out.println();
try {
int b = 3 / 0; // ArithmeticException
}catch(NullPointerException e) {
System.out.println(e);
System.out.println("프로그램 오류");
}catch(ArithmeticException e) {
System.out.println(e);
System.out.println("프로그램 오류");
}finally {
System.out.println("finally 영역");
}
System.out.println("프로그램 종료");
}
}
try~catch 사용예시
클래스인 AA를 메인에 가져와서 호출해도 값들이 각각 NULL값과 0으로 설정 되어있어 객체를 생성한후 출력을 한다면
NULL값과 0으로 뜨게되는데 b = 3 / 0;이 오류나는것을 Exception e을 이용하여 예외처리를 하였다
public class Ex03 {
public static void main(String[] args) {
// try {
// call();
// System.out.println("정상 처리");
// }catch(Exception e) {
// System.out.println(e);
// System.out.println("call()에서 예외처리 발생 main");
// }
try {
arr();
System.out.println("정상 처리");
}catch(Exception e) {
System.out.println(e);
System.out.println("arr()에서 예외처리");
}
}
public static void call()throws ArithmeticException{
// try {
// int i = 3 / 0;
// }catch(ArithmeticException e) {
// System.out.println(e);
// System.out.println("call()에서 예외처리 발생");
// throw e;
// }
try {
int i = 3 / 0;
}catch(ArithmeticException e){
System.out.println("call()에서 예외처리 발생");
throw e;
}
}
public static void arr() throws Exception{
try {
int arr[] = {1,2,3};
System.out.println(arr[3]);
}catch(Exception e) {
System.out.println(e);
System.out.println("arr()에서 예외처리 발생");
throw e;
}
}
}
throws 사용예시
예외처리가 발생하면 arr메서드를 thows를 이용하여 main 클래스에 보내 main메서드에서 예외처리를 시키는 코드이다
메인 메서드로 가는 이유는 메인 메서드에서 arr();으로 호출을 해줬기 때문이