JAVA Programming

Growing_HJ·2024년 5월 29일

일기장

목록 보기
12/51

2024.05.29. WED, <D + 9> , 예외처리

  • Exception(예외)
    => 코드로 해결할 수 있는 오류 (컴파일 에러 아님).
    => 일어날 수 있는 오류에 대비해, java에서 제공되는 문법을 활용해 해결
  • Exception 문법: try, catch, finally
    여러가지 예외처리에 대한 예제코드)
public class ExceptionEx1 {
	public static void main(String[] args) {
		int number = 100;
		int result = 0;
		for (int i = 0; i< 10; i++) {
			// 실행유지 or 정상종료 처리되도록 Exception Handling함
			try {	//Exception이 발생될 부분을 기입
				result = number/(int)(Math.random() * 10);
				System.out.println(result);
			} catch (ArithmeticException e) {	//발생한 예외에 대한 리포팅처리 
				System.out.println("0으로 나누기를 수행");
			}
			/** 0으로 나누는 경우, java.lang.ArithmeticException 발생
			 * 비정상 종료 => 문제점 리포팅 => 정상종료가 되도록 해야 함.**/
		}
	}
}
//예외처리2 - 개발자가 필요에 의해서 예외를 발생시키는 경우 (사용자 정의에 의한 예외)
public class ExceptionEx2 {
	public static void main(String[] args) {
		try {
			//1. Exception class의 인스턴스를 생성 -> 2. 인스턴스 던지면 됨 (throw사용)
			/**Exception ue = new Exceptioin ("고의로 예외를 발생시킨 경우)
			 * throw ue; **/
			
			//throw new Exception ("고의로 예외를 발생시킴");
			/**System.out.println(3);
			 * System.out.println(0/0);
			 * System.out.println(4);**/
		} catch (ArithmeticException ae) {
			if (ae instanceof Exception) {
				System.out.println("true");
			}
			System.out.println("에외 메시지 : " + ae.getMessage());
			System.out.println("ArithmeticException");
		} 
		catch (Exception e) {
			//ArithmeticException 는 Exception로 만들어진 파생클래스
			// 따라서 , 다형성으로 catch가 된 것.
			System.out.println("Exception");
			System.out.println("예외메시지 : " + e.getMessage());
		}
		//Exception 처리가 되었으므로, 정상종료가 됨.
		System.out.println(5);
		System.out.println("프로그램이 정상종료 되었음.");
	}
}
//예외처리3 - 메소드를 활용한 예외처리
// 메소드에서 Exception을 발생시켜 던지기, 예외처리 위임
public class Exception3 {
// 1. 메소드를 생성해보자
	static void method1() throws Exception{
		method2(); //예외처리 위임.
		/*try {
			method2();
		} catch (Exception e) {
			// TODO: handle exception
		}*/
	}
	static void method2() throws Exception{
		throw new Exception("method2(): 예외처리 발생 (예외처리 위임)");
	}
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			method1();// 위임받은 예외를 처리함
		} catch (Exception e) {
			// TODO: handle exception
		}
		// method1(); // 비정상 종료를 의미
		System.out.println("정상종료됨. ");
	}
}


0개의 댓글