본문 바로가기
수업(국비지원)/Java

[Java] chap9 : 예외처리 - Exception1(try, catch), Exception2(다중 catch 구문)

by byeolsub 2023. 4. 15.
  • try catch 구문
 예외 처리 : 발생된 예외를 정상적으로 처리하는 방법
  
  try catch 구문
    try 블럭 : 예외 발생 가능성이 있는 문장을 가진 블럭
    catch 블럭 : catch블럭이 속한 try블럭에서 예외 발생시 실행 되는 블럭

 

📌

package chap9;
/*
 * [결과]
 * 145
 * 1235
 */
public class ExceptionEx1 {
	public static void main(String[] args) {
		try {
		   System.out.print(1);
//		   System.out.print(2/0); //ArithmeticException 발생
		   System.out.print(2);
		   System.out.print(3);
		} catch(Exception e) {   
		   System.out.print(4);
		}
		System.out.println(5);
	}
}

 


  • 다중 catch 구문
 다중 catch 구문
    - 한개의 try블럭에 여러개의 catch 블럭이 존재
    - try블럭내에 발생가능한 예외가 여러개 있는 경우, 예외별로 다른 예외처리 가능.
    - 상위 예외클래스는 catch 구문의 하단에 배치해야 한다.

 

📌

package chap9;

public class ExceptionEx2 {
	public static void main(String[] args) {
//		System.out.println(args[0]); //try 구문 밖에서 발생된 예외는 catch 구문을 실행하지 못함
		try {
			System.out.println(args[0]); //ArrayIndexOutOfBoundsException 예외 발생
			System.out.println(10/1);    //ArithmeticException 예외 발생
			String s=null;  //객체 생성 안함. 
			System.out.println(s.trim()); //NullPointerException 예외 발생. 전산부로 연락하세요 메세지 출력
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("command 라인에 값을 입력하세요");
		} catch (ArithmeticException e) {
			System.out.println("0으로 나누지 마세요");
		} catch (Exception e) {   //그외 모든 예외 처리 
			System.out.println("전산부로 연락하세요 ");
			e.printStackTrace();
		}
	}
}