[Java] 03. Exception Handing

Yeonbo_ra·2024년 10월 12일

Java

목록 보기
3/6
post-thumbnail

1. Exception Hierarchy

Throwable

  • Error와 Exception의 상위 클래스

  • Throwable

    • Error
      • OutOfMemoryError
      • StackOverflowError
      • VirtualMachineError
      • etc.
    • Exception
      • RuntimeException
        • NullPointerException
        • ArrayIndexOutOfBoundsException
        • ClassCastException
        • etc.
      • IOException
      • SQLException
      • etc.

Error 클래스

  • 컴퓨터에 영향을 줄 수 있어서 발생. JVM이 찾아냄
  • 환경에 다뤄야 하는 부분
    ex) OutOfMemoryError, StackOverflowError, VirtualMachineError

Exception 클래스

  • 런타임 중에 발생. 직접 체크해야하는 부분
  • Checked : try-catch 구문으로 예외를 처리해야 하는 부분
    • IOException, SQLException, ClassNotFoundException
  • Unchecked : 코드 수정으로 처리해야 하는 부분
    • NullPointerException, ArrayIndexOutOfBoundsException
  • 예외의 상하 관계
    ex) FileNotFoundException < IOException < Exception

2. Try-Catch Block and Throw Clause

Try-Catch 블럭

try {
	// 예외를 찾을 수 있는 코드 넣기
} catch (ExceptionType2 e1) {
	// 오류 발생 시 실행할 구문
} catch (ExceptionType2 e2) {
	// 한 try에 여러 catch 사용 가능
} finally {
	// 오류 발생 여부 관계 없이 반드시 실행
}
  • try에서 예외가 발생되는 순간 바로 catch로 넘어간다. 예외 발생 시점 이후의 try 구문은 무시된다.
  • catch에 들어가는 예외는 작은 → 큰 순으로 적어야 한다.
  • Exception 클래스는 모든 예외의 상위 클래스, 어떤 예외라도 받을 수 있다.

Throw clause

  • 특정 메소드가 exception을 throw 할 수 있다고 경고하는 것
public void myMethod() throws IOException {

}
  • exception에 대한 경고가 있는 메소드는 반드시 try-catch로 처리해야한다.
    • 처리 위치는 상관이 없으나, 처리 안할시 오류 발생

3. Custom Exception

  • 사용자가 직접 만드는 예외
    • 클래스 정의 & 생성자로 예외 생성
      public class MyCustomException extends Exception {
      	public MyCustomException(String Message){ // 생성자
      		super(message);
      }
      → Exception 클래스 상속 받기
    • 예외가 들어갈 메소드 만들기 & 예외 던지기
      public class TestCustomException {
      	public void myMethod() thorws MyCustomException{
       		throw new MyCustomException("Custom error message");
       	}
      }
    • main : 예외가 들어간 메소드 실행 & 예외 처리
      public static void main(String[] args) {
      	TestCustomException test = new TestCustomException();
       	try{
       		test.myMethod();	
       	} catch (MyCustomException e) {
       		System.out.println("Caught custom exception: " + e.getMessage());
       	}
      }
profile
컴공 대학생의 공부기록

0개의 댓글