java

Step13_Exception (Exception 관리, RuntimeException, throw)

bono.html 2022. 8. 2. 17:54

 

 

MainClass03 (Thread.sleep)

 

MainClass03

 

Thread.sleep(5000); 을 작성하면 코드 오류가 뜨고 마우스를 올려두고  surround with try/catch를 누르면 자동으로 작성된다.

부모 클래스에 RuntimeException 이 없으면 try catch 없이 사용할 수 없다.

 

 

MainClass04 (File만들기, try catch)

 

MainClass04

createNewFile 메소드로 File을 만든다.

파일 업로드 오류(IOException) 예외 상황이 발생하면

printStackTrace 메소드를 실행한다. 콘솔에 자세한 경고 메시지 출력하는 코드이다.

 

 

MainClass05, SleepyException (RuntimeException, 예약어 throw)

예외 상황 인위적으로 만들기

 

SleepyException
MainClass05

 

프로그래머가 필요에 따라 예외 객체를 생성할 클래스를 직접 만들 수도 있다.
실행 중에 발생하는 예외를 발생 시키고 싶으면 RuntimeException 을 상속 받아서 만들면 된다.

 

Exception은 RuntimeException을 상속 받았는지 아닌지로 나눠서 봐야한다.
상속받지 않았다면 trycatch 문을 사용해야한다.

 

if(ranNum==5) { 
    throw new SleepyException("너무 졸려");
}

우연히 랜덤한 정수가 5 가 나오면 예외를 발생 시킨다.

throw 예약어와 함께 예외 객체를 생성하면 예외가 발생한다.

 

 

MainClass06, MyUtil (예외처리)

 

MyUtil
MainClass06
MainClass06

 

Thread.sleep 를 사용하려면 두가지 방법 중에 골라야 한다.

 

surround with try/catch

add throws declaration

 

후자를 선택하는 경우 메소드를 호출하는 쪽에서 예외처리를 해야한다.

그래서 MyUtil에서 예외처리를 한 draw 메소드는 MainClass06에서 오류 없이 잘 작동하지만 throws를 한 send 메소드는 MainClass06에서 다시 예외처리를 해줘야 했다.