Dart Exceptions
Run-time errors are known as Dart Exceptions. When the program is executed, it is raised. When the program runs internally and the Dart compiler discovers something inappropriate, the program does not communicate the error at compile time. The software then reports a run-time problem and terminates unexpectedly. We refer to this kind of error as an exception. As an illustration, we might divide a given number by zero or attempt to access the contents of the empty list.
The following categories of built-in exceptions are supported by Dart.
Sr. | Exceptions | Description |
---|---|---|
1. | DefferedLoadException | It is thrown when a deferred library fails to load. |
2. | FromatException | It is the exception which is thrown |
3. | IntegerDivisionByZeroException | It is thrown when number is divided by zero. |
4. | IOEException | It is the base class of input-output related exception. |
5. | IsolateSpawnException | It is thrown when an isolated cannot be created. |
6. | Timeout | It is thrown when a schedule timeout happens while waiting for an async result. |
The exception’s primary goal is to manage the run-time issue and keep the program from ending suddenly. In Dart, each exception is a subclass of the predefined class Exception. The following methods are available in Dart to deal with exceptions.
The try/on/catch Blocks
The code block that could potentially throw an exception is contained within the try block. When we need to specify the exceptions, we use the on block. When the handler need the exception object, it uses the catch block.
The catch block contains the code to handle the error if the try block discovers it and throws to it. There must be precisely one on/catch or one finally block after the try block.
Syntax
try {
// code that might throw an exception
}
on Exception1 {
// Specify the exception
}
Catch Exception2 {
// code for handling exception
}
The following things are important to keep in mind.
- Using numerous catch blocks, we can manage multiple exceptions.
- Since both the on and the catch blocks are mutually inclusive, we can associate them both with the try block.
The variable x is divided by the variable y, correspondingly, in the example that follows. When it tries to divide by zero, the code throws an error. The code to deal with the exception is contained in the on block. Let’s examine the code below.
Example
void main() {
int x = 12;
int y = 0;
int res;
try {
res = x ~/ y;
}
on IntegerDivisionByZeroException {
print('Cannot divide by zero');
}
}
Output
Cannot divide by zero
Explanation
The three variables, x, y, and res, were declared in the main() method of the code above. We wrote the questionable code in the try block and split the possible exception-throwing x by 0. After the try block identified the error, control was moved to the on block, which contains the error-handling code. The application did not halt its execution by using this.
Example
void main() {
int x = 12;
int y = 0;
int res;
try {
res = x ~/ y;
}
// It returns the built-in exception related to the occurring exception
catch(E) {
print(E);
}
}
Output
IntegerDivisionByZeroException
Example
void main() {
int x = 12;
int y = 0;
int res;
try {
res = x ~/ y;
}
on IntegerDivisionByZeroException catch(E) {
print(E);
}
}
Output
IntegerDivisionByZeroException
The Finally Block
Whether or not there is an exception, the finally block always runs. Following the try/on/catch, it executes unconditionally.
Below is the finally block’s syntax.
Syntax
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
finally { void main() {
int x = 12;
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
We implemented numerous interfaces in the College class in the example above. Every student and faculty member’s data is overriding in the college class. We generated the College class object and called the overriding methods. The outcome was printed.
Throwing an Exception
We have the option to firmly or expressly make an exception. Handling the explicitly raised exception is necessary to prevent the program from abruptly terminating. Below is the syntax.
Syntax
throw new Exception_name()
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
Explanation
We implemented numerous interfaces in the College class in the example above. Every student and faculty member’s data is overriding in the college class. We generated the College class object and called the overriding methods. The outcome was printed.
Custom Exceptions
Every exception in Dart is a subtype of the built-in class Exception, as we have already covered. By extending the current exception class, Dart offers the freedom to generate custom exceptions. Below is the syntax.
Syntax
class Custom_exception_Name implements Exception {
// can contain constructors, variables and methods
}
Example
class AmtException implements Exception {
String expMsg() => 'Entered Amount should be greater than zero';
}
void main() {
try {
withdraw_amt(-1);
}
catch(E) {
print(E.expMsg());
}
finally {
print('Ending requested operation.....');
}
}
void withdraw_amt(int amt) {
if (amt <= 0) {
throw new AmtException();
}
}
Output
Entered Amount should be greater than zero
Ending requested operation.....
Explanation
We defined a custom exception called AmtException in the example above. If the entered amount is outside of the allowed range, the code raises an exception, and the function call is contained within the try…catch block.