티스토리 뷰

생활코딩-java 수업을 듣고 중요 내용을 정리한 것입니다.


  • 소비자에서 생산자로
package Day20190720;

class Calculator{
	int left, right;
	
	public void setOprands(int left, int right) {
		this.left = left;
		this.right = right;
	}
	
	public void divide() {
		if(left == 0 || right == 0) {
			throw new ArithmeticException("0으로 나눌 수 없습니다.");
		}
		try {
			System.out.print("계산결과는 ");
			System.out.print(this.left/this.right);
			System.out.print("입니다.");
		}catch(Exception e) {
			System.out.println("오류가 발생했습니다. : ");
			System.out.println("\n\ne.getMessage()\n"+ e.getMessage());
			System.out.println("\n\ne.toString()\n"+e.toString());
			System.out.println("\n\ne.printStackTrace()");
			e.printStackTrace();
		}
	}
}

public class ExceptionEx1 {

	public static void main(String[] args) {
		Calculator c1 = new Calculator();
		c1.setOprands(10, 0);
		try {
			c1.divide();
		}catch(ArithmeticException e) {
			System.out.println(e.getMessage());
		}
	}

}

 

위의 예제와 같이 divide 내에서 예외를 처리할 수 있다.  throw는 예외를 발생시키는 명령이다. throw 뒤에는 예외 정보를 가지고 있는 예외 클래스가 위치한다. 자바 가상 머신은 이 클래스를 기준으로 어떤 catch 구문을 실행할 것인지를 결정한다. 또 실행되는 catch 구문에서는 예외 클래스를 통해서 예외 상황의 원인에 대한 다양한 정보를 얻을 수 있다. 이 정보를 바탕으로 문제를 해결하게 된다.  

 

기억할만한 주요 Exception들의 리스트

  • 예외의 여러가지 상황들
package Day20190720;

import java.io.IOException;

class E{
	void throwArithmeticException() {
		throw new ArithmeticException();
	}
	
	void throwIOException() {
		try {
			throw new IOException();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	void throwIOException2() throws IOException {
		throw new IOException();
	}
}

public class ExceptionEx5 {

	public static void main(String[] args) {
		
	}

}

둘 다 Exception을 발생시키고 있는데 왜 throwIOException은 컴파일 되지 않을까?

 

예외 클래스 간의 상속관계

 

Exception 클래스의 하위 클래스들의 목록

도대체 RuntimeException 클래스는 어떤 특이점이 있길래 부모 클래스인 Exception 클래스와 함께 언급되는 것일까? RuntimeException을 제외한 Exception 클래스의 하위 클래스들과 RuntimeException 클래스의 차이를 차바에서는 checked와 unchecked 라고 부른다. 

  • checked 예외 - RuntimeException을 제외한 Exception의 하위 클래스
  • unchecked 예외 - RuntimeException의 하위 클래스 

checked 예외는 반드시 예외처리를 해야 하는 것이고, unchecked는 해도 되고 안해도 되는 예외이다. (Error도 unchecked이다)

 

'Programming Language > Java' 카테고리의 다른 글

래퍼(wrapper) 클래스  (0) 2019.07.23
Object 클래스  (0) 2019.07.22
예외처리(Exception Handling) - 예외 던지기  (0) 2019.07.21
예외처리(Exception Handling) - 문법  (2) 2019.07.20
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
글 보관함