Dart Exception Handling With Examples
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 | Integer Division By Zero Exception Thrown when a number is divided by zero. |
2 | IO Exception Base class for all Input-Output related exceptions. |
3 | Deferred Load Exception Thrown when a deferred library fails to load. |
4 | Format Exception An exception is thrown when a string or some other data does not have an expected format and cannot be parsed or processed. |
5 | Isolate Spawn Exception Thrown when an isolate cannot be created. |
6 | Time out Thrown when a scheduled timeout happens while waiting for an async result. |
We divide our code that may create exceptions into blocks using try/on/catch blocks to handle these exceptions. The try block contains code that could potentially throw an exception. When the exception type must be provided, the block is utilized. When the handler requires the exception object, the catch block is used.
If the try block encounters an error, it passes control to the catch block, containing the code to manage the situation. An on/catch or a finally block always follows a try block.
Syntax:
try {
// code that might throw an exception
}
on Exception1 {
// Specifying exception
}
Catch Exception2 {
// Handling exception
Finally Block: In dart, the final block is used to include specific code that must be executed regardless of any errors. Although including the finally block is optional, if you do, it should come after the try and catch blocks have been completed.
Syntax:
try {
// code that may throw an exception
}
on Exception1 {
// Specifying exception
}
catch Exception2 {
// Handling exception
}
finally {
// This block always execute irrespective of exception.
}
Now let’s discuss the implementation of these blocks:
Using the try-catch block
Below is an example showing the usage of try and catch block handling. When the try block catches, the error control gets transferred to the catch block preventing the code stops abnormally.
Code:
void main() {
int a = 120;
int b = 0;
int result;
try {
result = a ~/ b;
}
//'E' return the built-in exception according to the exception occurred.
catch(E) {
print(E);
}
}
Output:
Unsupported operation: Result of truncating division is Infinity: 120 ~/ 0
Explanation: In the example above, we are trying to divide a number by zero, so it shows an exception for that.
Using the Finally Block
Irrespective of an exception, the finally block is always executed. After the try/on/catch, it executes unconditionally.
Code:
void main() {
int a = 120;
int b = 0;
int result;
try {
result = a ~/ b;
}
//'E' return the built-in exception according to the exception occurred.
catch(E) {
print(E);
}
finally{
print("Your execution has come to an end.");
print("You are in the finally block.");
}
}
Output:
Unsupported operation: Result of truncating division is Infinity: 120 ~/ 0
Your execution has come to an end.
You are in the finally block.
Explanation: In this example, we are using the case of a number divided by zero to show the working of try, catch and finally blocks.
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.
The output is
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.
The response of console
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.
And the expected result
Till now everything looks fine. What about the “finally” block. As said before it will get executed no matter what. Let’s explore
The expected messages on the console.
Stack Trace Exception
Stack Trace Exception: Stack trace helps you to trace the events that occurred before the exception was thrown
A Stack Trace is a list of the method calls that the application was in the middle of when an Exception was thrown. The most useful information is normally shown at the top of StackTraces, so you should always look at them from the ‘top down’. Sometimes this takes a lot of scrolling up!
Consider the try catch example code but this time with Stack Trace Exception.
Pretty simple just pass a parameter along with exception in catch block. Here is the output.
Comments
Post a Comment