CodeBlanks Logo Icon CodeBlanks

Exception hierarchy

Learn the exception hierarchy and custom exceptions.

Exception hierarchy

In Dart all problems derive from Object. Exception is an abstract interface; you define custom exceptions with class MyError extends Exception.

You build a hierarchy by extending Exception: class AppException extends Exception, class NetworkException extends AppException. Then on AppException catches AppException and its subclasses.

In a catch block on SpecificException catch (e) catches a specific type. This lets you handle different error types differently.

A custom exception example

A custom exception usually carries a message field: class AppException extends Exception { final String message; AppException(this.message); }.

To throw it write throw AppException('connection failed');. To catch it use try { ... } on AppException catch (e) { print(e.message); }.

on AppException catch (e) catches only AppException and its subclasses. A general catch (e) catches everything.

Practice A custom exception class

Define an AppException class that extends Exception with a final String message field and a constructor. In main throw AppException('connection failed') and catch it with on AppException catch (e), then print e.message.

Starter code

main.dart
// Define the AppException class, extend Exception

void main() {
  // throw AppException, catch it and print the message
}

Sample solution

main.dart
class AppException extends Exception {
  final String message;
  AppException(this.message);
}

void main() {
  try {
    throw AppException('connection failed');
  } on AppException catch (e) {
    print(e.message);
  }
}

Expected output

connection failed

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is the correct way to define a custom exception?

  • class MyError : Exception
  • Exception class MyError
  • class MyError extends Exception Correct answer
  • MyError implements new Exception

Explanation: in Dart you extend Exception with extends.

2 Extend Exception

Question
class AppException extends ____ { final String message; AppException(this.message); }
Answer
class AppException extends Exception { final String message; AppException(this.message); }

Explanation: Which base class should you extend?

3 Exception hierarchy parts

Term Meaning
Exception Base exception
extends Subclass keyword
throw Throwing
on ... catch Catching

All lessons in Intermediate