[JAVA] 예외처리

kbannie·2022년 11월 4일
0

JAVA

목록 보기
6/8
post-thumbnail

🎈예외 (Exception)

예외란 프로그램 실행 중에 예기치 못한 상황에서 발생하는 비정상적인 상황을 가리킵니다.

  • 정수를 0으로 나누기
  • 유효하진 않은 배열의 첨자를 사용한 선택식
  • 객체가 할당되지 않은 참조변수의 사용
  • 잘못된 형식의 콘솔 입력이나 파일 접근시의 문제
  • 메서드 호출에 의해 발생

🎈예외처리 (Exception Handling)

예외처리란 예외 발생 시 프로그램의 비정상적인 종료대신 계속해서 정상적인 수행을 할 수 있도록 처리하는 것입니다.

예외 객체 처리

  1. try ~ catch 문에 의해 직접 처리
  2. 메서드 호출측으로 던져짐 = throws

예외 객체

프로그램에서 예외도 하나의 객체로 표현되어 일반 객체처럼 클래스를 이용하여 정의되어 사용 가능합니다.

예외 클래스

java.lang.Throwable로부터 파생된 클래스로 throws할 수 있습니다.

예외 클래스의 종류와 구조

  • Exeption 클래스 : 덜 심각한 예외로 예외처리의 동반이 필수가 아닙니다.
    • Checked Exception : 반드시 예외처리를 해야지만 컴파일이 가능합니다.
    • Unchecked Exception : 필요에 따라 예외처리가 가능하며 하지 않아도 컴파일이 가능합니다.
      👉 RuntimeException
  • Error 클래스 : 더 심각한 예외로 에러라 불리며 예외처리의 동반이 필수입니다.

RuntimeException 클래스의 sub class

  • ArithmeticException : 0으로 나누는 경우에 발생
  • java.io.IOException : 입출력 동작의 실패

예외 메시지 표시 방법

Throwable 클래스의 멤버 메서드를 사용합니다.

  • String getMessage() : 예외 객체가 가지고 있는 에러 메시지를 반환합니다.
  • void printStackTrace() : 예외 발생 원인과 경로를 추적하여 콘솔에 표시합니다.

🎈예외 처리 방법

1. try~catch문

  • try문 : 예외가 발생할 가능성이 있는 실행문 (예외 발생 시 catch 문으로 전달)
  • catch문 : 예외 처리문
public class e1 {
	public static void main(String[] args) {
		int num1=3, num2=0;
		
		try {  //정수를 0으로 나누니 예외 발생 가능성 있음
			int result=num1/num2;  //exception
			System.out.println(result);
		}
        
		catch(ArithmeticException ae) {  //함수 매개변수 ae
			String str=ae.getMessage();
			System.err.println(str);
		}
	}
}

2. throws문

메서드 구현부에 기술하며 예외발생시 예외 처리를 현재 메서드를 호출한 곳으로 양도합니다. 즉, 언젠가는 try~catch문으로 처리해주어야 합니다.

  • throw <예외객체>
  • throw new <예외클래스생성자>
public class e3 {
	static int divide(int a, int b) throws ArithmeticException{
			int result=a/b;
			return result;	
			//예외 발생시 쓸데없는 값을 반환하는 것이 아닌 오류를 던짐
	}
	
	public static void main(String[] args) {
		int num1=3, num2=0;
		
		try { //함수로부터 던져진 오류를 main에서 처리함
			int result=divide(num1,num2); 
			System.out.println(result);
		}
		catch(ArithmeticException ae) { 
			String str=ae.getMessage();
			System.err.println(str);
			}
		System.out.println("끝");
	}
}

사용자 정의 예외

프로그래머가 직접 필요한 예외 클래스를 만들어 사용합니다.

//Account.java
public class Account {
	protected String accountNo;
	protected String name;
	protected int balance;
	
	public Account(String accountNo, String name, int balance) {
		this.accountNo=accountNo;
		this.name=name;
		this.balance=balance;
	}
	
	public int deposit(int amount) throws MalformedData{
		if(amount<0)
			throw new MalformedData(); 
		balance+=amount;
		return balance;
	}
	
	public int withdraw(int amount) throws MalformedData, OBException {
		if(amount<0)
			throw new MalformedData(); 
		
		if(balance<amount) {
			throw new OBException();
		}
		
		balance-=amount;
		return amount;

	}
	
	public void check() {
		System.out.println("잔액 조회 :"+balance);
	}
}
//Bank.java
public class Bank {
	
	public static void main(String[] args) {
		Account [] banks=new Account[2];
		banks[0]=new Account("11","aa",100);
		banks[1]=new Account("22","bb",200);

		try {
			int n=banks[0].deposit(-1000);
		}
		catch(MalformedData e) {
			String str=e.getMessage();
			System.err.println(str);
		}
		
		
		try {
			int n=banks[1].withdraw(3000);
		}
		catch(MalformedData e) {
			String str=e.getMessage();
			System.err.println(str);
		}
		catch(OBException e) {
			String str=e.getMessage();
			System.err.println(str);
		}
   }
profile
여행하는 데이터 사이언티스트🧙‍♂️

0개의 댓글

관련 채용 정보