What are Exceptions?
Part of the Logic & Flow section of Coddy's Dart journey — lesson 38 of 65.
When you run a program, things don't always go as planned. Sometimes your code encounters unexpected situations that it can't handle normally - these are called exceptions.
An exception is a runtime error that occurs while your program is executing. Unlike syntax errors that prevent your code from running at all, exceptions happen when your program is already running but encounters a problem it doesn't know how to solve.
Common situations that cause exceptions in Dart include trying to convert invalid text to a number (which creates a FormatException), accessing a list element that doesn't exist, or dividing by zero. When an exception occurs and isn't handled properly, your entire program will crash and stop running.
The key insight is that exceptions are predictable - you can anticipate where they might occur and prepare your code to handle them gracefully. This prevents crashes and allows your program to continue running even when something goes wrong.
Cheat sheet
An exception is a runtime error that occurs while your program is executing, unlike syntax errors that prevent code from running at all.
Common exceptions in Dart include:
FormatException- trying to convert invalid text to a number- Accessing a list element that doesn't exist
- Dividing by zero
When an exception occurs and isn't handled properly, your entire program will crash and stop running. Exceptions are predictable and can be handled gracefully to prevent crashes.
Try it yourself
This lesson doesn't include a code challenge.
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Advanced List Manipulation
List Properties: first & lastList State: isEmpty & isNotEmpReversing a ListAdding to a List: insertList Removal: removeWhereFinding in a List: indexOfSorting a ListShuffling a ListRecap - List Organizer4Advanced Map Manipulation
Iterating Over a MapChecking for Keys and ValuesMap Properties: keys & valuesConditional Add: putIfAbsentRemoving Entries from a MapNested MapsRecap - Inventory Update2Functional List Operations
Transforming with 'map'Filtering with 'where'Using '.toList()'Checking Conditions with 'any'Conditions with 'every'Finding with 'firstWhere'Recap - Data Filtering5Project: Shopping Cart Calc
Project SetupAdding Items to the Cart3Sets
What is a Set?Creating a SetAdding and Removing from SetsChecking for Elements in a SetConverting a List to a SetSet UnionSet IntersectionSet DifferenceRecap - Unique Guest List6Basic Error Handling
What are Exceptions?The 'try-catch' BlockCatching Exceptions with 'on'The 'finally' BlockThrowing an ExceptionRecap - Safe Division