Code&Data Insights

[ Java Programming ] Exception Handling (Checked Exception | Unchecked Exception) 본문

Computer Science/Java Programming

[ Java Programming ] Exception Handling (Checked Exception | Unchecked Exception)

paka_corn 2022. 7. 24. 09:48

 

 

Exception Handling 

(Checked Exception | Unchecked Exception)

 

 

 

[ Exception ]

- Exception(예외)란 프로그램이 핸들링 할 수 있는 오류를 말한다. 

 

- When something does not go as planned (프로그램이 원하는 방향으로 작동하지 않을때 사용) 

 

- Exception(예외처리) 하는 방법  : 

- 오류, 그 중 런타임 에러는 Error와 Exception으로 나뉜다. 

=> 오류의 경우 컴파일에러/런타임에러/논리적에러로 나뉜다. 예외처리를 할 수 있는 에러는 런타임에러, 그 중에서 exception만이 가능하다. 

=> Error의 경우에는 예외처리가 불가능하다. 

=> (ex) OutOfMemory와 같은 심각한 에러는 예외처리로 다룰 수 없다 

 

 

- Exception의 종류 : checked / unchecked exception

 

 

 

 

[ Checked Exception ]

- 예외 처리 필수 , 컴파일러가 예외처리 여부를 체크 

=> A method must declare that it might throw an exception

=> 반드시! try-catch문을 사용해서 예외를 처리해줘야 한다. 

 

- Most Exceptions are checked ( 대부분의 예외는 checked 예외이다. )

 

- Exception과 Exception class(base class) 의 child class(derived class).

 

- Compile time에 발생한다. 

=> IDE(Eclipse, IntelliJ)와 같은 통합개발환경 tool이 Complie시에 체크를 해준다. 

 

- 주로 사용자의 실수로 발생 

 

- (ex) IOException, SQLException 

 

 

 

 

 

[ Unchecked Exception ]

예외 처리 선택 , 컴파일러가 예외 처리 여부를 체크 안함

=> try-catch문을 쓰지 않고도 컴파일이 가능하다. 

 

- RuntimeException과 RuntimeException(base class)의 child class(derived class).

 

- runtime(실행 시) 발생 한다. 

 

- 주로 개발자의 실수로 발생 

 

- (ex) ArrayIndexOutOfBound, ArithmeticException, NullpointException

 

 

 

 

[ Exception Handling ]

예외를 처리하는 방법에는 try-catch문을 이용해 직접 처리하거나, 예외 선언(떠넘기기)가 있다. 

 

< Try-Catch >

: the basic way we use exceptions is by wrapping code in try-catch blocks

( try-catch문 안으로 코드를 넣어 예외처리하는 가장 기본적인 방법 )

 

 

< 예외를 선언하는 방법 >

: 메서드가 호출시 발생가능한 예외를 호출하는 쪽에 알리는 것. 

 

 

 

 

- throws와 throw 

throws : Exception Handling을 다루기 위해 사용

 

=> methods can declare that they throw exceptions (예외를 메서드에 선언)

=> methods have to declare thrown checked exceptions

=> Always try to be specific, don't just throw Exception

 

throw : '예외 상황'을 발생시키고자 할 때 

=> Create an exception instance

 

 

 

 

 

 

 

 

Comments