본문 바로가기
카테고리 없음

#11-2 / 외부클래스 + 예외처리

by eungSe__ 2024. 5. 16.
⚡ 메소드 형태의 오류처리 선언 및 호출 방법
throws : 해당 메소를 실행시 예외처리 구분자를 필수로 적용시키는 형태
메소드에서 throws 실행시 반드시 try,catch로 받아야함
(협업할때 주로 사용)

package oop2;
//메소드 형태의 오류처리 선언 및 호출 방법
public class ex5 {

	public static void main(String[] args) {
		ex5_box ex5 = new ex5_box();
		try { //try{try{}}는 x
		//해당 메소드에서 throws이므로 무조건 try~catch 이용			
			ex5.abc(5000, "500a"); 
		}catch(Exception e) {
			System.out.println(e);
			try { //재try로 실행하여 데이터를 다시 보냄(throws 이므로 무조건 사용)
				ex5.abc(5000, "500 0");	
			}catch(Exception e2) {
				System.out.println(e2);
				System.exit(0);
			}
		}
	}
}

class ex5_box {
	//예외처리를 기본적으로 적용 시킬 메소드
	  //받는쪽에서 예외처리를 해둠 - 보내는쪽에서 try,catch 써야함
	public void abc(int no, String z) throws Exception {
		//여긴 try,catch x - 여긴 처리만 하는곳
		int sum = no + Integer.parseInt(z);
		System.out.println(sum);
	}
}

 

⚡ 외부클래스 throw 메소드 응용편

[ Exception 라이브러리 사용 ]
throw는 예외처리가 발생되면 상대방에게 에러 코드를 전송하며 , 재전송을 요청

코드의 가장 아래에 작성하게되며,
throw = return과 비슷한 성격
예외처리 결과에 대한 값을 호출한 메소드로 다시 return 시킴
재처리를 해줘야함(받는쪽,보낸쪽 크로스체크)
package oop2;
//외부클래스 throw 메소드 응용편
public class ex6 {
	public static void main(String[] args) {
		ex6_box ex = new ex6_box();
		try { //throws 메소드 이용 - try걸어줌
			ex.abc("123");
		}catch(Exception e) {
			System.out.println(e);
		}
	}
}

class ex6_box{
	public void abc(String a) throws Exception,NumberFormatException {
		//코드에러 발생
		int k = Integer.valueOf(a) + Integer.valueOf("200a");
		//System.out.println(k);
		
		Exception ep = new Exception(); //Exception 라이브러리
		throw ep; 
	}
}

 

⚡ throws , throw 모두 사용
package oop2;
public class ex7 {
	public static void main(String[] args) {
		try {
			ex7_box ex = new ex7_box();
			ex.abc("ok");
		}catch(Exception e) {
			//상대방에서 처리된 사항을 확인하는 조건문
            
			System.out.println(e.getMessage()); 
			//throws 메소드의 문제사항 출력(상대방의 오류)
            
			if(e.getMessage() == null) {
				System.out.println("정상적으로 데이터를 처리하였습니다");
			}else {
				System.out.println("오류 발생!");
			}
		}
	}
}

class ex7_box {
	Exception ep = null;
	public void abc(String a) throws Exception{
		//1.성공 또는 실패 모두 무조건 전송메세지 발송	
//		if(a == "ok") {
//			String key = "abc123";
//			int keycode = Integer.valueOf(key);
//		}else {
//			this.ep = new Exception();
//			throw this.ep;
//		}
		
		//2. 정상적으로 처리가 되었을 경우 null로 처리가 됨 : 자기코드 오류확인시
		try {
			if(a == "ok") {
				String key = "123abc";
				int keycode = Integer.valueOf(key);
				System.out.println(keycode);
			}else if(a == "no") {
				System.out.println("정상적처리완료");
			}
		}catch(Exception e){ //상대방 코드에는 문제사항 미전달,자신의 코드오류만 출력 
			e.printStackTrace();
			this.ep = new Exception();
			throw this.ep;
		}
		
	}
}

 

⚡ try,catch,finally, throws,throw 모두 사용
package oop2;
import java.util.Scanner;

public class ex8 { //값을 보내고, 결과값을 받는 코드
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		//1번. 상대방이 throws라서 try~catch 작성
		try {
			System.out.println("첫번째 숫자를 입력하세요 : ");
			String a = sc.nextLine();
			System.out.println("두번째 숫자를 입력하세요 : ");
			String b = sc.nextLine();
			Integer result = new box8_box().files(a,b); //2번.
			//사용자 입력값 전송 및 결과 받음
			
			System.out.println("결과 : " + result);
		}catch(NumberFormatException nfe){
			System.out.println("데이터 전송 오류!");
		}catch(Exception e) { //7번. 오류된 사항 확인시킴
			System.out.println(e); //하단 throw에서 받은 e출력
		}finally { //8번. 라이브러리 종료
			sc.close(); //어찌됐든 일어나야하는 코드 작성
		}
	}
}

class box8_box{ //값을 받고, 산술연산 후 결과값을 보내는 코드
	public Integer files(String aa,String bb) throws Exception{
		int sum = 0;
		try { //3번. 문제상황 감지 위해 try~catch 사용(문제 없으면 2번 실행)
			sum = Integer.parseInt(aa) + Integer.parseInt(bb); //문자를 숫자 변환
		}catch(Exception e) { //4번.(3번 오류시)
			System.out.println("인자값 숫자변환 오류~!!!"); //5번.
			throw e; 
			//6번. 문제 발생 => throw로 상대방에게 오류를 넘겨버림(상대방 catch 실행)
		}

		return sum;
	}
}

 

⚡ 응용문제
package oop2;
/*
 [응용문제] 스캐너 미사용
 45 * 3 + 16 + 5 + 22 * 8 해당 계산된 최종값을 
 외부 클래스에 전송시킵니다.
 해당 외부클래스에서 짝수일 경우 예외오류를 발생시킵니다
 단, 홀수일 경우 "홀수값 입니다" 라는 결과값을 return으로 보냅니다.
 최종 메인 메소드에서 결과값을 출력시키는 코드를 작성하시오. 
 */

public class ex9 {

	public static void main(String[] args) {
		int sum = 45 * 3 + 16 + 5 + 22 * 8;
		try {
			ex9_box ex = new ex9_box();
			String resultmsg = ex.abc2(sum); //값 전송
			System.out.println(resultmsg); //리턴받은 결과값 출력
		}catch(Exception e) {
			//System.out.println(e.getMessage());  //try~catch 사용시에는 x
		}

	}

}

class ex9_box {
	public String abc2(Integer a) throws Exception { //try~catch 사용
		String msg = "";
		try {
			if(a%2 == 0) {
				throw new Exception("올바르지 않은 값입니다2");
			}else {
				msg = "홀수값입니다.";
			}
		}catch(Exception e) {
			System.out.println(e);
		}
				
		return msg;
	}
	
	public String abc(Integer a) throws Exception { //try~catch 사용x
		String msg = "";
		if(a%2 == 0) {
			/*
			Exception ep = new Exception("예외처리 발생함. 해당결과 짝수값");
			throw ep; //강제 catch 실행
			*/
			throw new Exception("예외처리 발생함. 해당결과 짝수값"); //위에 두줄 짧게 작성 
		}else {
			msg = "홀수값입니다";
		}
		
		return msg;
	}
}