예외 처리

Eungae's avatar
Dec 21, 2025
예외 처리

예외 (Exception)

프로그램이 실행되는 동안 발생할 수 있는 예외적인 상황
  • 예외를 처리해주지 않을 경우 프로그램이 종료됨. → 예외 처리 시 프로그램이 정상적으로 실행된다.
  • 모든 종류의 예외는 Exception 클래스를 상속 받아서 구성된다. == 모든 종류의 예외는 Exception 클래스의 하위 클래스.
 

종류

기본 예외

DeferredLoadException

필요한 시점에 로드되도록 설정한 라이브러리가 로드되지 못 했을 때 발생.
DeferredLoadException(String message)
  • message에 예외에 대한 설명 작성
 

FormatException

데이터가 처리 가능한 형태가 아니어서 데이터를 처리하기 어려울 때.
FormatException([String message = "", dynamic source, int? offset])
  • message : 예외에 대한 설명
  • source : 예외가 발생한 원인이 되는 것
String invalidNumber = "abc"; int result = int.parse(invalidNumber); void main(){ print(result); } // Uncaught Error, error: Error: FormatException: abc
 

IOException

입출력 관련 동작을 하는 중에 발생하는 오류
  • FileSystemException 파일에 접근할 수 없는 경우, 파일이 없는 경우, 파일을 찾을 수 없는 경우 등
  • HttpException
  • ProcessException
  • SignalException
  • SocketException
  • StdinException
  • TlsException
  • WebSocketException
IOException()
 

OSError

운영체제 레벨에서 발생하는 오류. 운영체제로부터 받은 오류에 대한 정보.
OSError([String message = "", int errorCode = noErrorCode])
message에는 운영체제가 제공하는 예외에 대한 설명이 들어간다.
운영체제가 설명을 제공하지 않을 경우 빈 문자열(” ”)이 적용된다.
errorCode에는 운영체제가 제공하는 오류 코드가 들어간다.
 

TimeoutException

비동기 결과를 기다리는 동안 특정 시간이 초과되었을 때 발생.
TimeoutException(String? message, [Duration? duration])
message : 시간 초과가 발생한 원인에 대한 설명
duration : 초과된 시간
 
 

사용자가 직접 정의한 예외 (커스텀 예외)

Exception 클래스를 상속 받아서 새로운 예외 클래스를 만든다.
class AgeException implements Exception { final String message; AgeException(this.message); }
class AgeException implements Exception { final String? message; AgeException(this.message); @override String toString() => message ?? 'AgeException이 발생했어요!'; }
예외 클래스도 @override로 재정의 할 수 있다.
 
<예시>
class AgeException implements Exception { final String? message; AgeException(this.message); @override String toString() => message ?? 'AgeException이 발생했어요!'; } void printAge(int age) { if (age < 0) { throw AgeException(null); } print(age); } void main() { try { printAge(-8); } catch (e) { print(e); // AgeException이 발생했어요! } }
 
 

예외에서 사용하는 키워드

발생한 예외를 처리하기 위한 경우

try

예외가 발생할 수 있는 코드를 넣는 부분. 예외 처리 구문 쓸 때 꼭 넣을 것!
try 의 코드 블록 실행 중에 예외가 발생하면, try 의 코드 블록에 있는 뒷 코드들은 실행되지 않는다.
try { // 예외가 발생할 수 있는 코드 }
 

catch

try의 코드 블록 실행 중에 예외가 발생했을 때 실행할 코드를 넣는 부분.
try의 코드 블록에서 예외가 발생하지 않으면 실행되지 않는다.
예외 처리 구문을 쓸 때 꼭 넣어야 하며, 개수에 제한이 없다.
catch (e) { print(e); }
발생한 예외의 객체가 catch의 매개변수로 전달된다.
 

on

try 의 코드 블록에서 발생할 수 있는 예외 중 특정 타입의 예외를 다루는 부분
예외 처리 구문을 쓸 때 넣지 않아도 된다.
단독 사용 불가. catch와 항상 같이 사용.
예외 타입이 특정되기 때문에 catch에 객체가 전달되었을 때 그 객체를 가지고 할 수 있는 동작이 더 많음.
notion image
on 으로 예외 타입을 특정하지 않으면 Exception 이 기본적으로 가지고 있는 4가지 요소만 사용할 수 있음.
notion image
on으로 예외 타입을 특정해주면 그 타입이 가지고 있는 요소들을 사용할 수 있다.
 
on IOException catch (e) { // IOException 이 발생했을 때 실행할 코드 }
 

finally

예외 발생 여부와 상관 없이 실행할 코드를 넣는 부분
try, catch를 모두 거친 후에 실행된다.
예외 처리 구문을 쓸 때 넣지 않아도 된다.
finally { // 예외 처리 후 실행할 코드 }
 

예시

void main() { try { String invalidNumber = "abc"; int result = int.parse(invalidNumber); print(result); } catch(e) { print(e); // FormatException: abc } }
void main() { try { String invalidNumber = "abc"; int result = int.parse(invalidNumber); print(result); } on FormatException catch(e) { print(e); // FormatException: abc } }
void main() { try { String invalidNumber = "abc"; int result = int.parse(invalidNumber); print(result); } on FormatException catch(e) { print(e); // FormatException: abc } finally { print("예외 처리 끝"); // 예외 처리 끝 } }
void main() { try { String invalidNumber = "123"; int result = int.parse(invalidNumber); print(result); // 123 } on FormatException catch(e) { print(e); } finally { print("예외 처리 끝"); // 예외 처리 끝 } }
 
 

의도적인 예외

특정 경우에 예외를 의도적으로 발생시키기 위해 Exception 클래스나 Error 클래스를 통해 생성한 또는 상속 받은 객체를 던진다.
void printAge(int age) { if (age < 0) { throw Exception ("나이는 0 이상일 것"); } print(age); } void main() { try { printAge(-8); } catch (e) { print(e); // Exception: 나이는 0 이상일 것 } }
class PrintAge { int age; PrintAge(this.age); void printAge() { if (age < 0) { throw Exception("나이는 0 이상일 것"); } print(age); } } void main() { try { PrintAge printAge = PrintAge(40); printAge.printAge(); } catch (e) { print(e); // 40 } }
 
Share article

나새끼메이커