[java] 자바의 예외처리(Exception Handling). try ~ catch 와 throws 의 간단한 이해.

예외(Exception)
– 프로그램 실행중에 발생되는 의도하지 않은 문제
– 예외가 발생하면 프로그램은 비정상 종료된다.

public class Test{

	public static void main(String[] args)  { 
		
		System.out.println("프로그램 시작");
		
		int num = 2 / 0; // 예외발생
		
		System.out.println("종료"); // 실행안됨
	}
}

 

예외처리(Exception Handling)
– 발생된 예외 때문에 프로그램이 비정상 종료되는 것을 방지하고 정상 종료 되도록 처리하는것

예외처리 첫번째 방법 try ~ catch
– 예외처리 매커니즘
1. 프로그램 실행
2. try 내에서 예외발생
3. JVM은 예외를 처리할 수 있는 예외 클래스를 찾이서 해당 클래스의 객체를 생성한다.
4. 생성된 객체의 참조값은 catch 블록의 변수에 저장된다.(생성된 객체와 catch블록에 명시된 클래스가 다르면 예외처리 실패. 적절한 예외클래스를 지정해야함)
5. 예외처리 코드실행
6. 프로그램 정상종료

finally
– finally 블록은 프로그램 진행이 try 블록으로 넘어오면 예외발생 여부와 관계없이 실행된다.

public class Test {

	public static void main(String[] args) {

		System.out.println("프로그램 시작");
		try {
			int num = 2 / 0;	// 예외발생
			System.out.println("실행 안됨"); // 이 문장은 실행안됨 
		} catch (ArithmeticException e) {
			System.out.println( e.getMessage() ); // 예외를 사용자에게 알려줌
		} finally {
			System.out.println("예외발생과 무관하게 실행"); // 예외발생과 관계없이 실행된다.
		}
		System.out.println("종료");
	}
}

 

예외처리 두번째 방법 throws 를 이용한 예외처리
– 호출한 곳으로 예외처리를 넘기는 방법
– 생성된 예외클래스 대신에 다른 예외클래스를 이용해서 예외를 처리할때 사용.
주로 사용자 정의 예외클래스로 예외를 처리하는 경우

public class Test {

	public static void main(String[] args) {

		System.out.println("프로그램 시작");

		try {
			age(-1);
		} catch (UserException e) {
			System.out.println(e.getMessage());
		}
		System.out.println("종료");
	}

	public static void age(int age) throws UserException {	// throws UserException : 호출한 곳으로 넘겨서 처리하겠다는 선언

		if (age < 1) {
			throw new UserException("사용자 나이가 1 보다 작다.");	// 예외 클래스 객체 생성 (사용자 정의 예외클래스)
		}
	}
}

class UserException extends Exception {	// 사용자 정의 예외 클래스
	public UserException(String message) {	// 전달된 문자열은 getMessage 메소드 호출시 출력
		super(message);
	}
}

 

명시적으로 특정 예외 클래스를 정의 하여 예외처리(사용자 정의 예외클래스 사용X)

public class Test {

	public static void main(String[] args) {

		System.out.println("프로그램 시작");

		try {
			age(-1);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		System.out.println("종료");
	}

	public static void age(int age) throws Exception {	// throws UserException : 호출한 곳으로 넘겨서 처리하겠다는 선언

		if (age < 1) {
			throw new Exception("사용자 나이가 1 보다 작다.");	// 예외 클래스 객체 생성
		}
	}
}

 

답글 남기기