Dart Exception Handling
Exception Class –
An exception is any runtime error that leads to abrupt termination of the program. It helps in addressing the error programmatically. It is aimed to be caught and should contain useful message to be displayed so that the compilation can continue.
Constructors
- Exception –
Implementation –
factory Exception([var message]) = > _Exception(message);
Properties
- HashCode=
Returns the hash code for a numerical value, and it returns the same value for int and doubles when the value provided is the same.
Implementation = int get hashchode;
- Runtime Type=
Represents the type of runtime an object has.
Implementation = Type get runtimeType;
Methods
- noSuchMethod –
This method is invoked when a non-existent method or property is accessed.
Implementation =
@pragma("vm:entry-point")
external dynamic noSuchMethod(Invocation invocation);
- toString( )=
Converts a given number into an equivalent shortest string and returns the same.
Implementation = external String toString( );
Dart Exceptions
These are the run-time errors that occur when the program gets executed. This error doesn’t show up at the time of compilation error, and the program is terminated abnormally.
Example – If we try to access the file that actually does not exist.
The aim of having exception handling in any programming language is to handle the run-time error and preventing the program from terminating abruptly.
Following is the list of types of built-in exceptions :
Sr. |
Exceptions |
Description |
1. |
DefferedLoadException |
It is thrown when a deferred library fails to load. |
2. |
FromatException |
It is the exception which is thrown when a string or some other data
does not have an expected format and cannot be parsed. |
3. |
IntegerDivisionByZeroException |
It is thrown when number is divided by zero. |
4. |
IOException |
It is the base class of input-output related exception. |
5. |
IsolateSpawnException |
It is thrown when an isolate cannot be created. |
6. |
Timeout |
It is thrown when a schedule timeout happens while waiting for an
async result. |
The try/on/catch Blocks
The try block is used to hold the block of code that might throw an exception. We use on block when the exception type is required to be specified. While, the catch block is used when the handler needs the exception object.
If the try block falls through any error, it throws that error to the catch block which then handles the error using the code. The try block must be followed by either exactly one on/ catch or one finally block.
Consider the syntax of exception handling : -
try {
// code that might throw an exception
}
on Exception1 {
// specify the exception
}
Catch Exception2 {
// code for handling exception
}
Remember the following points with respect to exception handling :-
- We can handle the multiple exceptions using more than one on / catch block.
- There is mutually inclusion between the on block and the catch block that means we can associate both the on block and catch block with the try block.
In the following example, the variable x is divided by the y variable respectively. The code is thrown when it tries to divide by the zero. The on block consists of the code to handle the exception. Let's understand the following code.
Example - Using the on block
void main( ) {
int x = 15 ;
int y = 0 ;
int res ;
try {
res = x ~/ y ;
}
on IntegerDivisionByZeroException {
print( ' Cannot divide by zero ' ) ;
}
}
Output
Cannot divide by zero
Explanation :
In the above code, three variables x, y and res have been declared in main( ) function. As we know that the division of a number by 0 is undefined, we write the suspected code in the try block. The try block found the error and transfer the control to the on block that has the code to handle the error. By doing so, the program didn’t terminate abruptly.
Let's understand the following example using the catch block.
Example - Using the catch Block
void main( )
{
int x = 5 ;
int y = 0 ;
int res ;
try {
res = x ~/ y ;
}
catch( E ) {
print( E ) ;
}
}
Output
IntegerDivisionByZeroException
Consider the same code with the on…catch block
void main( ) {
int x = 5 ;
int y = 0 ;
int res ;
try {
res = x ~/ y ;
}
on IntegerDivisionByZeroException catch( E ) {
print( E ) ;
}
}
Output
IntegerDivisionByZeroException
The Finally Block
The finally block always executes irrespective of any exception present or not in the program. It executes unconditionally after the try/on/catch.
The syntax of finally block is given below:
try {
// code that may be throw an exception
}
on Exception1 {
// exception handling code or specifying the exception
}
catch Exception2 {
// code for exception handling
}
finally {
// code that should always execute; whether exception or not.
}
Example –
Consider the following code in Dart that explains the finally block
finally
{ void main( ) {
int x = 5 ;
int y = 0 ;
int res ;
try {
res = x ~/ y ;
}
on IntegerDivisionByZeroException {
print( ' Cannot divide by zero ' ) ;
}
print( ' Finally block always executed ' ) ;
}
}
Output
Cannot divide by zero
Finally block executed
Explanation
Even though the division is undefined here and therefore the program must ideally throw an exception but since we used ‘finally’ here the program still executed.
Throwing an Exception
An exception can be raised explicitly or forcefully using the ‘throw’ keyword. The explicitly raised exception should be handled to avoid the program from existing abruptly.
Syntax:
throw new Exception_name( )
Consider the following code in Dart that explains the above point,
Example -
main( ) {
try {
check_marks( -10 ) ;
}
catch( e ) {
print( ' The marks cannot be negative ! ' ) ;
}
}
void check_marks( int marks ) {
if( marks < 0 ) {
throw new FormatException( ) ; // Raising explanation externally
}
}
Output
The marks cannot be negative !
Custom Exceptions
As we discussed above, each of the exception in dart is the subtype of the built-in class Exception. Dart provides the flexibility to create custom exception by extending the existing exception class. The syntax is given below.
Syntax: Defining the Exception
class Custom_exception_Name implements Exception {
// can contain constructors, variables and methods
}