Exception Handling is one of the main core aspects of any programming language and it is one of the best practice to follow. Like any other rich programming language, Dart offers Exception Handling. We will understand this concept and I will show you Dart Exception Handling With Examples.
What is Exception Handling
Exception is a runtime unwanted event that disrupts the flow of code execution. It can be occured because of programmer’s mistake or by wrong user input.
To handle such events at runtime is called Exception Handling.
Types of Exceptions in Dart
There are quite a few built-in exceptions handling methods in Dart. Let’s focus on some of the main exceptions and their description
No | Exception and Description |
1 | IntegerDivisionByZeroException Thrown when a number is divided by zero. |
2 | IOException Base class for all Input-Output related exceptions. |
3 | DeferredLoadException Thrown when a deferred library fails to load. |
4 | FormatException An exception is thrown when a string or some other data does not have an expected format and cannot be parsed or processed. |
5 | IsolateSpawnException Thrown when an isolate cannot be created. |
6 | Timeout Thrown when a scheduled timeout happens while waiting for an async result. |
The syntax of typical Exception Handling in Dart looks like this.
try { //Logical code block } catch (e) { // On exception catch the code here. }
In Dart Exceptions can be handle via
- Try: In the try block, we write the logical code that can produce the exception
- Catch: Catch block is written with try block to catch the general exceptions: In other words, if it is not clear what kind of exception will be produced. Catch block is used.
- On: On block is used when it is 100% sure what kind of exception will be thrown.
- Finally: The finally part is always executed but it is not mandatory.
As for now, we have some understanding of exceptions and how can we handle them. Let do this via code.
Dart Exception Handling With Examples
In this tutorial, we will focus only on IntegerDivisionByZeroException. First of all, write an exception-free code.
void main() { try { int firstInput = 20; int secondInput = 4; int result = firstInput ~/ secondInput; print('The result of $firstInput divided by $secondInput is $result'); } catch (e) { print('Exception occurs: $e'); } }
The output is
The result of 20 divided by 4 is 5
Now suppose the secondInput value is 0. In this case, there will be an exception and it is pretty much sure its IntegerDivisionByZeroException. In this case, the “on” block can be used along with “try” block.
void main() { try { int firstInput = 20; int secondInput = 0; int result = firstInput ~/ secondInput; print('The result of $firstInput divided by $secondInput is $result'); } on IntegerDivisionByZeroException { print('The division by 0 is causing Exception '); } }
The response of console
The division by 0 is causing Exception
Imagine there is a huge logical coding block with integer values and other data types. It is not sure what can be the cause of the Exception. In that case, the “catch” block is a good option. Catch block when not sure what kind of exception can be thrown.
Just to keep is simple. The same code will be used but with catch block.
void main() { try { int firstInput = 20; int secondInput = 0; int result = firstInput ~/ secondInput; print('The result of $firstInput divided by $secondInput is $result'); } catch (e) { print('Exception occurs: $e'); } }
And the expected result
Exception occurs: IntegerDivisionByZeroException
Till now everything looks fine. What about the “finally” block. As said before it will get executed no matter what. Let’s explore
void main() { try { int firstInput = 20; int secondInput = 0; int result = firstInput ~/ secondInput; print('The result of $firstInput divided by $secondInput is $result'); } catch (e) { print('Exception occurs: $e'); } finally { print('There is an Exception occurred but I am still getting called'); } }
The expected messages on the console.
Exception occurs: IntegerDivisionByZeroException There is an Exception occurred but I am still getting called
Stack Trace Exception: Stack trace helps you to trace the events that occurred before the exception was thrown.
Consider the try catch example code but this time with Stack Trace Exception.
void main() { try { int firstInput = 20; int secondInput = 0; int result = firstInput ~/ secondInput; print('The result of $firstInput divided by $secondInput is $result'); } catch (e, s) { print('Exception occurs: $e'); print('STACK TRACE\n: $s'); } }
Pretty simple just pass a parameter along with exception in catch block. Here is the output.
Exception occurs: IntegerDivisionByZeroException STACK TRACE :#0 int.~/ (dart:core/runtime/libintegers.dart:18:7) #1 main (file:///Users/Waheed/IdeaProjects/FlutterRDart/bin/main.dart:5:29) #2 _startIsolate.<anonymous closure=""> (dart:isolate/runtime/libisolate_patch.dart:289:19) #3 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12) </anonymous>
NEXT: Learn how to write better code with custom exception handling class. It will boost your coding style.
Well, that is pretty much all. We have covered dart exception handling with examples. Hope you liked it.