본문 바로가기
  • developer
  • challenge
이론수업

자바 throws 예외 떠넘기기 문법

by 빵승 2024. 1. 15.

public class Main2 {

 

public static void main(String[] args) {

 

//throws: 예외 떠넘기기..문법

 

try {

int x=divide(10,0);

System.out.println("x : "+x);

}catch(ArithmeticException e) {

System.out.println("divide 메소드가 떠넘기 예외를 대신 처리해줌");

}

 

 

 

 

}

 

//두 수를 파라미터로 전달 받아 나눗셈의 결과를 리턴해주는 기능 메소드

//예외가 발생할 가능성이 있는 코드에서 try-catch문을 사용하기 어려운 상황도 있음.

// static int divide(int a,int b) {

// try {

// return a/b;

// }catch (ArithmeticException e) {

// System.out.println("예외발생");

//

// }

// return b;

 

 

//그래서 예외가 발생하면 예외처리를 호출하는 쪽으로 던져버리기..throws

static int divide(int a, int b) throws ArithmeticException{

return a/b; //예외발생은 이곳에서..

}

 

}

//throw : 코드를 통해서 예외를 강제로 발동!!

try {

System.out.println("aaa");

//강제로 예외 발생 - 억지로 catch영역으로 이동시키는 문법

throw new Exception();

 

 

 

}catch(Exception e) {

System.out.println("예외 발생!");

System.out.println("==============");

}

 

//[활용예]

//메소드의 계산을 요청했을때 그 결과가 절대 음수가 나오지 않았으면..

//혹시 음수가 나오면 이를 예외하고 프로그래밍 하고 싶다면?

int n;

 

try {

n=aaa(10,5);

n=aaa(10,15);

 

System.out.println("n:"+n);

}catch(Exception e) {

System.out.println("음수 결과는 싫어요");

}

 

 

static int aaa(int a, int b) throws Exception{

if(a<b) {

throw new Exception();

 

}

return a-b;

}

 

}