[자바] 예외 처리 throw, throws

seulki·2022년 10월 11일
0

[java]

목록 보기
8/11
post-thumbnail

🗝️ 예외처리

프로그램 실행 중 발생하는 오류 중에서 처리가 가능 한 것을 의미


🎈예외 처리 자세히 알아보러가기!

🎈 다중, 이중, 중첩 try - catch문 알아보러가기!



🗝️ throw

프로그래머가 고의로 예외를 발생 시킬 때 사용하는 방법

<구조>

Exception e = new Exception("Exeption");
throw e;

예시 )

public static void main(String[] args) {

		try {
			Exception e = new Exception("고의 예외");
			throw e; //고의로 예외를 던지겠다.
		} catch (Exception e) {
			System.out.println("예외 발생");
			System.out.println(e.getMessage());
		}
	}
  • Exception 객체 생성 후, 고의로 예외를 발생시켰다.
  • 예외가 발생되었으니, catch문 무조건 실행된다.


🗝️ throws

예외가 발생했을 경우, 현재 메서드가 예외를 처리하지 않고,
자신을 호출한 쪽으로 예외 처리에 대한 책임을 넘기는 것

<구조>

void method() throws Exception{...}

예시 1 )

public static void main(String[] args) {

		try {
			methodA();
		} catch (Exception e) {
			System.out.println("메인에서 처리");
		}
	}

	public static void methodA() throws Exception{
		methodB();
	}
	
	public static void methodB() throws Exception{
		methodC();
	}
	
	public static void methodC() throws Exception{
		Exception e = new Exception();
		throw e; //예외 발생
	}
    1. maintry문에서 methodA 호출
    1. methodA에서 methodB 호출
    1. methodB에서 methodC 호출
    1. methodC에서 Exception 객체 생성
      throw예외 강제 발생시킴.
    1. methodC에서 예외가 발생되었지만, methodC를 호출한
      methodB예외 처리 넘김
    1. methodB에서는 자신을 호출methodA예외 처리 넘김
    1. methodA에서는 자신을 호출main문으로 예외 처리 넘김
    1. main문catch문에서 예외 처리

예시 2 )

public static void main(String[] args) {
		int age = -19;
		try {
			ticketing(age);
		} catch (AgeException e) {
			e.printStackTrace();
		}
		
	}
	
	public static void ticketing(int age) throws AgeException {
		if(age < 0) {
			throw new AgeException("나이 입력이 잘못되었습니다.");
		}
    }
 public class AgeException extends Exception{

	public AgeException () {}
	public AgeException(String message) {
		super(message);
	}
}   
    1. try문에서 ticketing(age) 메서드 호출
    1. ticketing 메서드에서 if문 조건에 의해 AgeException 발생하여 객체 생성
    1. AgeException 생성자에 String으로 문자열 전달됨
    1. AgeException이 상속받은 부모 클래스인 Exception에
      문자열 message로 전달하며 객체 생성됨.
    1. ticketing 메서드에서 throws를 통해 자신을 호출한 main문으로
      예외 처리 넘김
    1. main문의 catch문에서 e.printStackTrace() 호출
profile
웹 개발자 공부 중

0개의 댓글