Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Dart Exception Handling

Dart Exception Handling

An exception is an error event that occurs while a program is running.

Good exception handling lets a program degrade gracefully when it encounters an error instead of crashing outright.

This chapter introduces try/catch/finally, throwing exceptions with throw, catching specific types with on, and rethrowing with rethrow in Dart.


try / catch / finally basics

The try block holds code that may throw an exception, the catch block catches and handles it, and the finally block executes whether or not 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 will not execute

 

}

catch

(

e

)

{

   

// e is the exception object

    print

(

'Exception caught: $e'

)

;

 

}

 

// Get exception and stack trace info

 

try

{

    List

<

int

numbers

=

[

1

,

2

,

3

]

;

    print

(

numbers

[

10

]

)

;

 

// Access an out-of-bounds index

 

}

catch

(

e

,

stackTrace

)

{

   

// e is the exception, stackTrace is the call stack

    print

(

'RUNOOB exception: $e'

)

;

    print

(

'Stack info:\n$stackTrace'

)

;

 

}

 

// finally: executes whether or not an exception occurs

 

try

{

    print

(

'Attempting operation...'

)

;

   

int

result

=

5

~/

0

;

    print

(

'This line will not execute: $result'

)

;

 

}

catch

(

e

)

{

    print

(

'Error: $e'

)

;

 

}

finally

{

   

// Code in the finally block always executes, often used to clean up resources

    print

(

'Resource cleanup done (finally always executes)'

)

;

 

}

}



捕获到异常: IntegerDivisionByZeroException

RUNOOB 异常: RangeError (index): Invalid value: Not in inclusive range 0..2: 10

Stack trace:

#0      List.[] (dart:core-patch/growable_array.dart:264)

#1      main (file:///...)

...

尝试执行操作...

出错: IntegerDivisionByZeroException

清理资源完成(finally 总是执行)

The finally block is best suited for resource cleanup, such as closing files and releasing database connections. Even if there is a return in try or catch, finally still executes.


Throwing exceptions with throw

Use the throw keyword to proactively throw an exception.

Dart allows throwing any object as an exception (not just subclasses of Exception), but the best practice is to throw a subclass 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 the custom exception

void

validateAge

(

int

age

)

{

 

if

(

age

<

0

)

{

throw

InvalidAgeException

(

age

)

;

 

}

 

if

(

age

150

)

{

   

throw

InvalidAgeException

(

age

)

;

 

}

  print

(

'Age $age validated'

)

;

}

// Throw a built-in exception

int

divide

(

int

a

,

int

b

)

{

 

if

(

b

==

0

)

{

   

throw

ArgumentError

(

'Divisor cannot be 0'

)

;

 

// Use a built-in exception

 

}

 

return

a

~/

b

;

}

void

main

(

)

{

 

// Test the custom exception

 

try

{

    validateAge

(

5

)

;

 

}

catch

(

e

)

{

    print

(

e

)

;

 

}

 

try

{

    validateAge

(

200

)

;

 

}

catch

(

e

)

{

    print

(

e

)

;

 

}

  validateAge

(

25

)

;

 

// Normal case

 

// Test throwing a built-in exception

 

try

{

    divide

(

10

,

0

)

;

 

}

catch

(

e

)

{

    print

(

'RUNOOB error: $e'

)

;

 

}

}



InvalidAgeException: 无效的年龄: -5(年龄必须在 0 到 150 之间)

InvalidAgeException: 无效的年龄: 200(年龄必须在 0 到 150 之间)

年龄 25 验证通过

RUNOOB 错误: Invalid argument(s): 除数不能为 0

Difference between Exception and Error: Exception is an expected error the program can handle (such as network timeout or missing file); Error is unexpected and usually indicates a program bug (such as type error or null pointer). Your code should catch Exception rather than Error.


Catching specific types with on

The on keyword can catch by exception type, making error handling more precise.

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 exceptions

    print

(

'RUNOOB error: cannot divide by zero'

)

;

 

}

on FormatException

catch

(

e

)

{

   

// Catch a format exception and get its info

    print

(

'RUNOOB format error: ${e.message}'

)

;

 

}

on RangeError

{

   

// Only catch range errors

    print

(

'RUNOOB error: index out of range'

)

;

 

}

catch

(

e

)

{

   

// Fallback: catch all other exceptions

    print

(

'Unknown error: $e'

)

;

 

}

finally

{

    print

(

'Operation finished\n'

)

;

 

}

 

// Example of matching in order

  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 -> range exception'

)

;

   

}

catch

(

e

)

{

      print

(

'$op -> other exception: $e'

)

;

   

}

 

}

}

int

performOperation

(

String operation

)

{

 

switch

(

operation

)

{

   

case

'divide_by_zero'

:

     

return

10

~/

0

;

 

// Throw IntegerDivisionByZeroException

   

case

'parse_error'

:

     

int

.

parse

(

'not_a_number'

)

;

 

// Throw FormatException

     

return

0

;

   

case

'out_of_range'

:

     

var

list

=

[

1

,

2

,

3

]

;

     

return

list

[

100

]

;

 

// Throw RangeError

   

case

'normal'

:

     

return

42

;

   

default

:

     

throw

Exception

(

'Unknown operation'

)

;

 

}

}



RUNOOB 错误: 不能除以零

操作结束



--- Testing different operations ---

divide_by_zero -> 除零异常

parse_error -> 格式异常

out_of_range -> 范围异常

The order of on and catch matters: Dart matches exception types from top to bottom. More specific exception types should come first, more general ones later. If catch (e) is placed first, the later on clauses will never execute.


Rethrowing with rethrow

Sometimes you need to do some handling after catching an exception (such as logging) and then let the exception continue to propagate upward.

The rethrow keyword rethrows the currently caught exception, preserving the original stack trace.

Example

// Simulate a multi-layer call scenario

void

databaseOperation

(

)

{

  print

(

' Connecting to database...'

)

;

 

throw

Exception

(

'RUNOOB database connection failed'

)

;

}

void

serviceLayer

(

)

{

 

try

{

    print

(

' Service layer: calling database operation'

)

;

    databaseOperation

(

)

;

 

}

catch

(

e

)

{

   

// Log first, then rethrow

    print

(

' [Log] database operation exception: $e'

)

;

    rethrow

;

 

// Preserve the original exception and stack, and continue to propagate upward

 

}

}

void

controllerLayer

(

)

{

 

try

{

    print

(

'Controller layer: handling request'

)

;

    serviceLayer

(

)

;

 

}

catch

(

e

,

stackTrace

)

{

   

// The outermost catch handles it

    print

(

'Controller layer caught the exception'

)

;

    print

(

'Error info: $e'

)

;

    print

(

'Return to the user: "Service temporarily unavailable, please try again later"'

)

;

 

}

}

void

main

(

)

{

  controllerLayer

(

)

;

  print

(

'\n--- The difference between rethrow and throw e ---'

)

;

 

// Demonstrate the difference between rethrow and throw e

 

try

{

   

try

{

     

throw

FormatException

(

'Original exception'

)

;

   

}

catch

(

e

)

{

     

// throw e: resets the stack trace, losing the original call location

      print

(

'Using throw e (original stack lost)...'

)

;

     

throw

e

;

 

// The stack starts from here

   

}

 

}

catch

(

e

,

stack

)

{

    print

(

'Caught: $e'

)

;

    print

(

'Stack points here (not the original location):\n$stack'

)

;

 

}

}



控制器层: 处理请求

  服务层: 调用数据库操作

  正在连接数据库...

  [日志] 数据库操作异常: Exception: RUNOOB 数据库连接失败

控制器层捕获到异常

错误信息: Exception: RUNOOB 数据库连接失败

给用户返回: "服务暂时不可用,请稍后重试"



--- The difference between rethrow and throw e ---

使用 throw e(丢失原始堆栈)...

捕获: FormatException: 原始异常

堆栈指向这里(不是原始位置):

...

The difference between rethrow and throw e is crucial: rethrow preserves the full stack trace of the original exception, making it easy to locate the root cause; throw e resets the stack, starting over from the current position. When you need to keep propagating an exception after logging, use rethrow.


Best Practices for Exception Handling

Practice Description
Only catch exceptions you can handle Do not blindly catch all exceptions just to avoid errors. If you do not know how to handle it, let it propagate upward
Catch by type Use on to specify the exception type, avoiding a single catch that swallows all exceptions
finally cleans up resources Resources such as files and network connections are closed in finally
Do not swallow exceptions Catching an exception but doing nothing (an empty catch block) is dangerous; at least log it
Use rethrow When you need to keep propagating the exception after logging, use rethrow rather than throw e
Exception messages should be specific throw Exception('Database connection failed: 192.168.1.1:3306') is more useful than throw Exception('Something went wrong')