gwooden_코린이

java_예외 강제 발생_221130(8일차) 본문

java/8일차

java_예외 강제 발생_221130(8일차)

gwooden22 2022. 11. 30. 15:27
728x90

예외 강제 발생은 코드문이 잘 작동되고 있나 테스트 할 때 쓰임

package 예외처리;

public class Sample {

	public static void main(String[] args) {
		//throw thorws
		
		System.out.println("프로그램 시작");
		
		try {
			throw new Exception("예외 발생");
		} catch(Exception e) {
			System.out.println(e.getMessage());
		}
		System.out.println("프로그램 종료");
		

	}

}


예외 떠넘기기 throws

 

package 예외처리;

public class Main {

	public static void main(String[] args) {

		Div d = new Div();
		
		try {
			d.div(5, 0);
		} catch(Exception e) {
			System.out.println("메인 catch");
		}

	}

}

package 예외처리;

import java.util.concurrent.ExecutionException;

public class Div {
	
	public void div(int a, int b) throws Exception { //throws Exception 예외를 떠넘겨 줄 거다
		try {
			System.out.println(a/b);
		} catch (Exception e) {
			System.out.println("메서드 catch");
			throw new Exception("0으로 나눌수 없다");
		}
	}

}


package 예외처리;

public class Main {

	public static void main(String[] args) {

		Div d = new Div();
		
		try {
			d.div(5, 0);
		} catch(Exception e) {
			System.out.println(e + "메인 catch");
		}

	}

}

package 예외처리;

import java.util.concurrent.ExecutionException;

public class Div {
	
	public void div(int a, int b) throws Exception { //throws Exception 예외를 떠넘겨 줄 거다
		try {
			System.out.println(a/b);
		} catch (Exception e) {
			System.out.println("메서드 catch");
			throw e;
		}
	}

}

 

728x90
Comments