** 예외처리 ( exception handling) **

* 예외처리란?

- 프로그램 실행시 발생할 수 있는 예기치 못한 예외의 발생에 대비한 코드를 작성하는 것

- 목적 : 예외 발생시 실행중인 프로그램의 갑작스런 비정상 종료를 막고, 비정상 종료를 막아 정상적인 실행 상태를 유지할 수 있도록 하는 것

- 구조 

try{
		예외처리하길 원하는 실행코드;
}

// catch는 여러개 사용가능함
catch(Exception1 e1){
		Exception1이 발생했을 경우, 처리하기위한 문장
}

catch(Exception2 e2){
		Exception2이 발생했을 경우, 처리하기위한 문장
}

....

finally{
		예외발생 여부와 상관없이 무조건 실행될 코드
}

 

 

프로그램이 실행 중 어떤 원인의 의해서 오작동을 하거나 비정상적으로 종료되는 경우를 프로그램 에러 또는 오류하고 함.

프로그램이 실행되는 도중 발생하는 예외를 처리하기 위해

try / catch / finally 문을 사용

컴파일 에러 - 컴파일 시에 발생하는 에러
런타임 에러 - 실행 시에 발생하는 에러
논리적 에러 - 실행은 되지만, 의도와 다르게 동작하는 것

 

* 자바에서 실행 시 발생할 수 있는 프로그램 오류

- 에러(error) : 프로그램 코드에 의한 수습될 수 없는 심각한 오류

- 예외(exception) : 프로그램 코드에 의해서 수습될 수 있는 오류

 

예외가 발생하더라도 프로그래머가 이에대한 적절한 코드를 미리 작성해 놓아 프로그램이 비정상적으로 종료되는 것을 막는 것을 의미함.

 

- 예외 클래스 계층구조 : 모든 예외의 최고 조상은  Exception클래스

 

FileNotFoundException

ClassNotFoundException

DataFormatException

 

ArrayIndexOutOfBoundsException




** 예제 exec Pakage _ MySample1129 (예외처리) **

package exec;

public class MySample1129 {

	public static void main(String[] args) {
		// 예외처리
		
		int[] a = {2, 0};
		int b = 4;
		
		//int c =a[2];		//먼저 실행 후 오류 확인
		
		try {
			int c = b / a[2];				//int c = a[2];
			System.out.println("c " + c);
		}
		catch(ArrayIndexOutOfBoundsException e){
			System.out.println("배열 인덱스 오류 발생");
		}
//		catch(ArithmeticException e) {
//			System.out.println("0으로 나눌수 없습니다. : " + e);
//		}
		
		//프로그램은 위에서 아래로 흐르기에 가장 최고조상인 Exception 은 가장 아래에 있어야 오류 안난다.
		catch(Exception e) {
			System.out.println("뭔지몰라 오류 발생 : " + e);
		}
		finally {	
			System.out.println("무조건 실행됨");
		}
		
		System.out.println("try~catch 끝.");
	}

}

** 예제 MySample1129 _ 2 (예외처리) **

package exec;

public class MySample1129_2 {

	public static void main(String[] args) {
		// 예외처리
		//0으로 나누었을 떄 "0으로 나눌 수 없습니다." 메세지 출력 후 계속 진행
		int number = 10;
		int result = 0;
		int i;
		
//		try {
//			for(i = 0 ; i < 10 ; i++) {
//				result = number/(int)(Math.random( )* 10);
//				System.out.println("result " + result); 
//			} 
//		}
//		catch(ArithmeticException e) {
//			System.out.println("0으로 나눌 수 없습니다.: " + e);
//		}
//		
//		
//			for(i = 0 ; i < 10 ; i++) {
//				try {
//					result = number/(int)(Math.random( )* 10);	//0~9
//					System.out.println("result " + result);
//				}
//				catch(ArithmeticException e) {
//					System.out.println("0으로 나눌 수 없습니다.: " + e);
//				}
//				 
//			} 
		
		//실행순서
		System.out.println("1");
		
		try {
			System.out.println("2");
			
			int a = 5 / 0;
			
			System.out.println("3");
		}
		catch(Exception e){
			System.out.println("4");
		}
		finally {
			System.out.println("4-2");
		}
		
		System.out.println("5");
		
	}
}

** 예제 MySample1129_3 (예외처리) **

package exec;

public class MySample1129_3 {

	public static void main(String[] args) {
		// 예외처리
		System.out.println("1");
		
		try {
			System.out.println("2");
			System.out.println(2 / 0);
			System.out.println("3");
		}
		catch(ArithmeticException e) {
			System.out.println("4");
			
			if(e instanceof ArithmeticException)
				System.out.println("true");
			
			System.out.println("ArithmeticException");
			e.printStackTrace();		//디버깅용
			
			
			System.out.println("예외 메세지 : " + e.getMessage());
		}
		catch(Exception e) {
			System.out.println("5");
			System.out.println("예외 메세지 : " + e.getMessage());
		}
		
		System.out.println("6");
	}
}

** 예제 MySample  1129_4 (예외발생시켜보기)**

package exec;

public class MySample1129_4 extends Exception{

	MySample1129_4(String a){
		super(a);
	}
	
	public static void main(String[] args) {
		//예외발생
		
		try {
			MySample1129_4 e = new MySample1129_4("일부러 오류 발생 시켰음.");
			//Exception e = new Exception("일부러 오류 발생 시켰음.");
			throw e;		//예외를 발생시키는 throw
		}
		catch(Exception e) {
			System.out.println("에러메세지 : " + e.getMessage());
		}
		
		System.out.println("프로그램 정상 종료 되었음.");
	}
}

** 예제 MySample 1129_5 (메서드예외) **

package exec;

public class MyClass1129_5 {

	public static void main(String[] args) {
		
		// 예외처리 - 메서드 예외
		// 예)void method() throws Exception1,Exception2,.....{		}
		
		try {
			method1();
			System.out.println("555555555555555");
		}
		catch(Exception e) {
			System.out.println("e.message : " + e.getMessage());
		}
		
		System.out.println("main 끝.");
	}
	
	//메소드 예외처리 : throws Exception 있으면 모든 예외를 나를 호출한 곳에서 try/catch.
	//throws Exception 메서드에 예외가 발생하면 더이상 실행하지 않고 나를 호출한 곳으로 돌아간다.
	static void method1() throws Exception{		
		System.out.println("111111111111111");
		method2();
		System.out.println("222222222222222");
	}
	
	static void method2() throws Exception{
		System.out.println("333333333333333");
		int c = 5 / 0;
		System.out.println("444444444444444");
	}
}

** 예제 MySample 1129_6 ( 예외처리 - finally블럭 ) **

package exec;

public class MySample1129_6 {

	public static void main(String[] args) {
		// 예외처리 - finally블럭
		
		try {
			startInstall();
			copyFiles();
			//deleteTempFiles();
		}
		catch(Exception e) {
			e.printStackTrace();
			//deleteTempFiles();
		}
		finally {
			deleteTempFiles();		//try/catch 둘다사용해야하는 경우는 보통 finally로 빼준다.
		}
		
		method1();
		System.out.println("method1() 실행 끝나고 main으로 돌아옴.");
	}
	
	static void startInstall() {
		System.out.println("프로그램 설치에 필요한 준비작업하는 영역..");
	}
	
	static void copyFiles() {
		System.out.println("파일들을 복사하는 영역..");
	}
	
	static void deleteTempFiles() {
		System.out.println("임시파일들 삭제하는 영역..");
	}
	
	static void method1() {
		try {
			System.out.println("method1() 실행시작");
		}
		catch(Exception e) {
			e.printStackTrace();
		}
		finally {
			System.out.println("method1() finally블럭실행");
		}
	}
}

** 예제 MySample 1129_7 (클래스 예외처리 - 예외클래스 생성 후 다른클래스 메소드에서 예외처리) **

package exec;

import java.util.Scanner;

public class MySample1129_7 {

	static Scanner scn = new Scanner(System.in);	//main메소드가 static이라서
	
	public static int inputScore() throws ScoreException{	//예외 클래스 만든것을 메소드에서 예외처리함
		int score = scn.nextInt();
		
		if(score < 0 || score > 100){
			ScoreException ex = new ScoreException("점수는 0~100점 사이 입력하세요.");
			throw ex;
		}
		
		return score;
	}
	
	public static void main(String[] args) {
		// 예외처리(클래스)
		
		try {
			System.out.print("국어 점수 입력>");
			int kor = inputScore();
			System.out.println("국어 점수는 " + kor + "점 입니다.");
			
			System.out.print("영어 점수 입력>");
			int eng = inputScore();
			System.out.println("영어 점수는 " + eng + "점 입니다.");
		}
		catch(ScoreException ex) {
			System.out.println("오류메세지 : " + ex.getMessage());
		}
		finally {
			System.out.println("프로그램 종료합니다.");
		}
	}
}

class ScoreException extends Exception{			//예외처리클래스
	ScoreException(){
		super("점수 입력 오류");
	}
	
	ScoreException(String nsg){
		super(nsg);
	}
}

** 문제 MySample1129_8 (예외처리) **

// 예외처리 - 문제
/*
 * 20번 반복해서 랜덤발생을 0~9까지 발생시킨후 랜덤값으로 나눈 결과를 화면에 출력하되 0으로 나누면 오류 발생함.
 * ArithmeticException 에 대한 예외처리를 적용하고 예외에 대한 출력은 0으로 처리하고, 0으로 나눈 횟수 발생한
 * 건수를 최종 출력하는 프로그램
 * 출력예)
 * 16
 * 20
 * 11
 * 0 -> 랜덤발생이 0으로 되어 예외처리부분.
 * 33
 * 100
 * ...
 * 0 발생 건수 : 1건
 * 단, number = 100; 으로 초기 설정 후 (int)(Math.random() * 10); 처리함
 */

package exec;

public class MySample1129_8 {

	public static void main(String[] args) {
		// 예외처리 - 문제
		/*
		 * 20번 반복해서 랜덤발생을 0~9까지 발생시킨후 랜덤값으로 나눈 결과를 화면에 출력하되 0으로 나누면 오류 발생함.
		 * ArithmeticException 에 대한 예외처리를 적용하고 예외에 대한 출력은 0으로 처리하고, 0으로 나눈 횟수 발생한
		 * 건수를 최종 출력하는 프로그램
		 * 출력예)
		 * 16
		 * 20
		 * 11
		 * 0		-> 랜덤발생이 0으로 되어 예외처리부분.
		 * 33
		 * 100
		 * ...
		 * 0 발생 건수 : 1건
		 * 단, number = 100; 으로 초기 설정 후 (int)(Math.random() * 10); 처리함
		 */
		
		int number = 100;
		int result, cnt = 0;
		int i;
		
//		for (i = 0 ; i < 20 ; i++) {
//			try {
//				result = number / (int)(Math.random() * 10);
//				System.out.println(result);
//			}
//			catch(ArithmeticException a) {
//				result = 0;
//				cnt++;
//				System.out.println(result);
//			}
//		}	
//		System.out.println("0 발생 건수 : " + cnt);
		
//		//다른방법 (깔끔함)
//		for (i = 0 ; i < 20 ; i++) {
//			try {
//				result = number / (int)(Math.random() * 10);
//			}
//			catch(ArithmeticException a) {
//				result = 0;
//				cnt++;
//			}
//			finally {
//				System.out.println(result);
//			}
//		}	
//		System.out.println("0 발생 건수 : " + cnt);	
		
		
		//결과는 위화 동일하며 try~catch문을 사용하지 않고 프로그램 구현.
		

		for (i = 0 ; i < 20 ; i++) {
			
			int tmp = (int)(Math.random() * 10);
			
			if(tmp != 0) {
				result = number / tmp;
			}
			
			else {
				result = 0;
				cnt++;
			}
			System.out.println(result);
		}	
		System.out.println("0 발생 건수 : " + cnt);
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

+ Recent posts