본문 바로가기

청년취업아카데미/DayLog

[ Java ] Day 02 - ② 예외 처리

# 오류란 무엇인가?

  • 프로그램이 실행 중 어떤 원인에 의해서 오작동을 하거나 비정상적으로 종료되는 경우 이러한 결과를 초래하는 원인을 에러 또는 오류라고 한다.
  • 자바에서는 실행(Run Time)시 발생할 수 있는 오류에러(Error)예외(Exception) 두가지로 구분한다.
  1. 에러(Error) : 프로그램 코드에 의해서 수습될 수 없는 심각한 오류
  2. 예외(Exception) : 프로그램 코드에 의해서 수습될 수 있는 다소 미약한 오류
  • 자바에서는 실행시 발생할 수 있는 오류(Exception or Error)를 클래스로 정의해두었다.

예외 클래스의 구조

  • 예외 처리의 종류
  1. 예외 복구: try - catch - finally 문
  2. 예외 회피 : throws 던지기
  3. 예외 전환: catch문에서 다른 예외로 전환 throw OtherException();

 

# 예외처리 예제 1. FileNotFoundException

...더보기
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileNotFoundExceptionEx {
	public static void main(String[] args) {
		FileReader reader;
		char[] buffer = new char[100];
		String file_name = ".classpath3";
		try {
			reader = new FileReader(file_name);
			reader.read(buffer, 0, 100);
			String str = new String(buffer);
			System.out.println("읽은 건" + str);
			reader.close();
		} catch (FileNotFoundException e) {
			System.out.println("그런 파일 없슴당");
		} catch (IOException e) {
			System.out.println("읽다가 에러났슈");
		} finally {
			System.out.println("어쨌거나 읽었어요!");
		}
	}
}

 

# 예외처리 예제 2. ClassNotFoundException

...더보기
public class ClassNotFoundExceptionEx {
	static void callDriver() throws ClassNotFoundException{
		Class.forName("oracle.jdbc.driver.OracleDriver");
		System.out.println("complete");
	}
	public static void main(String[] args) {
		try {
			callDriver();
		}catch(ClassNotFoundException e) {
			System.err.println("can't find class");
		}catch (Exception e) {
			System.out.println(e.getMessage());
		}finally {
			System.out.println("System exit");
		}
	}
}

 

# 예외처리 예제 3. ArithmeticException

...더보기
import java.util.Scanner;

public class ArithmeticExceptionEx {
	public static void main(String[] args) {
		double result =0;
		int num1=0;
		int num2 =0;
		
		Scanner sc = new Scanner(System.in);
		do {
			try {
				System.out.println("첫번째 숫자를 입력하세요 > ");
				num1 = Integer.parseInt(sc.nextLine());
				if(num1 == 0) break;
				
				System.out.println("두번째 숫자를 입력하세요 > ");
				num2 = Integer.parseInt(sc.nextLine());
				
				result = (double)num1/num2;
				System.out.printf("%d / %d = %d",num1,num2,result);
			}catch(ArithmeticException e){
				System.out.println("숫자만 가능합니다");
			}catch(Exception e) {
				System.out.println("\n[나머지 Error]\n"+e.getMessage());
				e.printStackTrace();
				break;
			}finally {
				System.out.println("어쨌든 끝");
			}
		}while(true);
	}
}

 

# 예외처리 예제 4. Exception 클래스 직접 작성하기 - MyException

...더보기
public class MyException extends Exception{
	@Override
	public String getMessage() {
		String ErrMsg;
		ErrMsg = "아니 10보다 크다니";
		return ErrMsg;
	}
}
class MyException1 extends Exception{
	@Override
	public String getMessage() {
		String ErrMsg;
		ErrMsg = "사장님 1000만원 넘 많아요, 좀 적당이 합시다!";
		return ErrMsg;
	}
}
class MyException2 extends Exception{
	@Override
	public String getMessage() {
		String ErrMsg;
		ErrMsg = "사장님 100만원 보다 적어요!! 이 뭡니까?";
		return ErrMsg;
	}
}

public class MyExceptionEx {
	public static void main(String[] args) {
		try {
			int kkk = Integer.parseInt(args[0]);
			if (kkk < 100)
				throw new MyException1();
			else if (kkk < 1000)
				throw new MyException2();
			System.out.println("정상 실행.");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.err.println("실행 매개 값의 수가 부족합니다.");
			System.err.println("[실행 방법]");
			System.err.println("java MyExceptionEx num1");
		} catch (MyException1 e) {
			e.printStackTrace();
		} catch (MyException2 e) {
			e.printStackTrace();
		}
	}
}