YouTip LogoYouTip

Dart Exception Handling

An exception is an error event that occurs during program execution. Good exception handling allows programs to degrade gracefully when encountering errors instead of crashing directly. This chapter introduces try/catch/finally in Dart, throwing exceptions with throw, catching specific types with on, and rethrowing with rethrow. * * * ## try / catch / finally Basics The try block contains code that may throw exceptions, the catch block catches and handles exceptions, and the finally block executes regardless of whether an exception occurs. ## Example void main(){ // Basic try-catch try{ int result =10~/0;// Division by zero throws an exception print('Result: $result');// This line won't execute }catch(e){ // e is the exception object print('Caught exception: $e'); } // Get exception and stack trace try{ List numbers =[1,2,3]; print(numbers);// Access out-of-bounds index }catch(e, stackTrace){ // e is the exception, stackTrace is the call stack print('TUTORIAL Exception: $e'); print('Stack trace:n$stackTrace'); } // finally: executes regardless of whether an exception occurs try{ print('Attempting to execute operation...'); int result =5~/0; print('This line won't execute: $result'); }catch(e){ print('Error: $e'); }finally{ // Code in finally block always executes, commonly used for resource cleanup print('Cleanup complete (finally always executes)'); } } Caught exception: IntegerDivisionByZeroException TUTORIAL Exception: RangeError (index): Invalid value: Not in inclusive range 0..2: 10Stack trace:#0 List.[] (dart:core-patch/growable_array.dart:264)#1 main (file:///...)...Attempting to execute operation...Error: IntegerDivisionByZeroExceptionCleanup complete (finally always executes) > The finally block is best suited for resource cleanup, such as closing files, releasing database connections, etc. Even if there are return statements in try or catch, finally will still execute. * * * ## throw - Throwing Exceptions You can actively throw exceptions using the throw keyword. Dart allows throwing any object as an exception (not just subclasses of Exception), but best practice is to throw subclasses of Exception or Error. ## Example // Custom exception class class InvalidAgeException implements Exception { final int age; final String message; InvalidAgeException(this.age) : message ='Invalid age: $age (age must be between 0 and 150)'; @override String toString()=>'InvalidAgeException: $message'; } // Function using custom exception void validateAge(int age){ if(age 150){ throw InvalidAgeException(age); } print('Age $age validated successfully'); } // Throw built-in exception int divide(int a,int b){ if(b ==0){ throw ArgumentError('Divisor cannot be 0');// Use built-in exception } return a ~/ b; } void main(){ // Test custom exception try{ validateAge(-5); }catch(e){ print(e); } try{ validateAge(200); }catch(e){ print(e); } validateAge(25);// Normal case // Test throwing built-in exception try{ divide(10,0); }catch(e){ print('TUTORIAL Error: $e'); } } InvalidAgeException: Invalid age: -5 (age must be between 0 and 150)InvalidAgeException: Invalid age: 200 (age must be between 0 and 150)Age 25 validated successfully TUTORIAL Error: Invalid argument(s): Divisor cannot be 0 > Difference between Exception and Error: Exception is expected and can be handled by the program (such as network timeout, file not found); Error is unexpected and usually indicates program bugs (such as type errors, null pointer). Your code should catch Exception, not Error. * * * ## on - Catching Specific Types The on keyword allows catching by exception type for more granular error handling. ## Example void main(){ // Catch different exceptions by type try{ // Simulate different types of exceptions int result = performOperation('divide_by_zero'); print('Result: $result'); } on IntegerDivisionByZeroException { // Only catch division by zero exception print('TUTORIAL Error: Cannot divide by zero'); } on FormatException catch(e){ // Catch format exception, also get exception info print('TUTORIAL Format error: ${e.message}'); } on RangeError { // Only catch range error print('TUTORIAL Error: Index out of bounds'); }catch(e){ // Fallback: catch all other exceptions print('Unknown error: $e'); }finally{ print('Operation endedn'); } // Example of sequential matching print('--- Testing different operations ---'); for(var op in['divide_by_zero','parse_error','out_of_range','normal']){ try{ performOperation(op); } on IntegerDivisionByZeroException { print('$op -> Division by zero exception'); } on FormatException { print('$op -> Format exception'); } on RangeError { print('$op
← Dart TypedefDart Interfaces And Mixins β†’