Your Dart code can throw and catch exceptions. Exceptions are errors indicating that something unexpected happened.
To manually throw or raise an exception use throw
statement.
throw FormatException('Expected at least 1 section');
You can also throw arbitrary objects:
throw "Some Error";
When you throw an exception, the program is terminated unless it is handled by try
and catch
block.
Catching, or capturing, an exception stops the exception from propagating. Catching an exception gives you a chance to handle it:
try { breedMoreLlamas(); } on OutOfLlamasException { buyMoreLlamas(); }
The following code shows how to specify multiple catch
statement when you want to handle different specific type of exceptions:
try { breedMoreLlamas(); } on OutOfLlamasException { // A specific exception buyMoreLlamas(); } on Exception catch (e) { // Anything else that is an exception print('Unknown exception: $e'); } catch (e) { // No specified type, handles all print('Something really unknown: $e'); }
You can use either on
or catch
or both. Use on
when you need to specify the exception type. Use catch
when your exception handler needs the exception object.
You can specify one or two parameters to catch()
. The first is the exception that was thrown, and the second is the stack trace.
try { // ยทยทยท } on Exception catch (e) { print('Exception details:\n $e'); } catch (e, s) { print('Exception details:\n $e'); print('Stack trace:\n $s'); }
To ensure that some code runs whether or not an exception is thrown, use a finally
clause. If no catch
clause matches the exception, the exception is propagated after the finally
clause runs:
try { breedMoreLlamas(); } finally { // Always clean up, even if an exception is thrown. cleanLlamaStalls(); }
The finally
clause runs after any matching catch
clauses:
try { breedMoreLlamas(); } catch (e) { print('Error: $e'); // Handle the exception first. } finally { cleanLlamaStalls(); // Then clean up. }