Dart Exceptions are anomalous conditions that a program might encounter during execution. An exception occurs when a program encounters an unexpected event that disrupts the normal flow of instructions. For instance, when a function is invoked, and the requested operation ends up terminating abruptly, an exception is thrown.
Exception handling is a crucial aspect of Dart programming. It helps to handle errors and exceptions gracefully, preventing the program from ending the requested operation prematurely. Without proper exception handling, a Dart program might throw an exception, leading to unexpected results or even causing the program to crash.
In Dart, there are two types of exceptions: predefined and custom exceptions. Predefined exceptions are part of the Dart core library. They include common exceptions that might occur during the execution of a program, such as FormatException and IntegerDivisionByZeroException.
On the other hand, Dart also allows programmers to define custom exceptions. These are user-defined exceptions that extend the built-in class Exception. For instance, a programmer might define a Class AmtException implements Exception to handle specific scenarios that are not covered by the predefined exceptions. Custom exceptions provide a way to signal that a particular condition has occurred, allowing the catch block to handle the exception appropriately.
The Exception class in Dart plays a vital role in the process of exception handling. It serves as the base class for all exceptions. When an exception occurs, an object of the Exception class or its subclass is instantiated and thrown. This exception object carries information about the error that occurred, which can be used to handle the exception and recover from the error.
Here's a simple example of how an exception object is created and thrown:
1void main() { 2 try { 3 throw Exception('This is a Dart exception'); 4 } catch (e) { 5 print(e); 6 } 7}
Dart provides a built-in class Exception that serves as the base class for all exceptions. However, to handle specific error conditions that are not catered to by the built-in exceptions, Dart allows the creation of custom exception classes.
A custom exception class can be created by implementing the Exception class. The custom exception class can then be used to throw an exception explicitly when a specific condition is met. Here's an example of a custom exception class:
1class AmtException implements Exception { 2 String errMsg() => 'Amount should not be less than zero'; 3} 4 5void main() { 6 try { 7 var amt = -1; 8 if (amt < 0) { 9 throw AmtException(); 10 } 11 } catch (e) { 12 print(e.errMsg()); 13 } 14}
Creating an instance of the Exception class or a custom exception class is straightforward. You simply use the new keyword followed by the name of the exception class. This instance can then be thrown using the throw keyword. Here's an example:
1void main() { 2 try { 3 throw new FormatException('Invalid Format'); 4 } catch (e) { 5 print(e); 6 } 7}
In the above code, an instance of the FormatException class is created and thrown. The catch block then catches this exception and prints the error message.
The try-catch block in Dart is a critical part of exception handling. The try block contains the code that might throw an exception, while the catch block captures and handles the exception. If an exception occurs within the try block, the program control is immediately transferred to the corresponding catch block.
1void main() { 2 try { 3 var res = 12 ~/ 0; 4 print("The result is $res"); 5 } catch (e) { 6 print("Exception occurred: $e"); 7 } 8}
The catch block in Dart is used to catch and handle exceptions that are thrown within the try block. The catch block can catch all types of exceptions or specific exceptions, depending on how it's defined. If a specific exception type is defined in the catch block, only exceptions of that type will be caught.
1void main() { 2 try { 3 var res = 12 ~/ 0; 4 print("The result is $res"); 5 } catch (e, s) { 6 print("Exception occurred: $e"); 7 print("Stack trace: $s"); 8 } 9}
The finally block in Dart is used to ensure that certain code gets executed regardless of whether an exception was thrown or not. The finally block is always executed after the try and catch blocks, even if an exception is thrown and caught.
1void main() { 2 try { 3 var res = 12 ~/ 0; 4 print("The result is $res"); 5 } catch (e) { 6 print("Exception occurred: $e"); 7 } finally { 8 print("This is the finally block"); 9 } 10}
The try-catch block in Dart can also handle multiple exceptions. You can define multiple catch blocks for a single try block, each handling a different type of exception.
1void main() { 2 try { 3 var res = 12 ~/ 0; 4 print("The result is $res"); 5 } on IntegerDivisionByZeroException { 6 print("Cannot divide by zero"); 7 } catch (e) { 8 print("Unknown exception: $e"); 9 } 10}
In the above code, the try block is followed by two catch blocks. The first catch block handles the IntegerDivisionByZeroException, while the second catch block handles all other exceptions.
Handling exceptions in Dart involves using the try-catch block. The try block contains the code that might throw an exception, and the catch block captures and handles the exception. If an exception occurs within the try block, the program control is immediately transferred to the corresponding catch block.
1void main() { 2 try { 3 var res = 12 ~/ 0; 4 print("The result is $res"); 5 } catch (e) { 6 print("Exception occurred: $e"); 7 } 8}
While both exception handling and error handling deal with unexpected or anomalous conditions, there is a difference between the two. An exception typically represents an error that occurs during the normal operation of a program, and it can often be handled gracefully. On the other hand, an error usually represents a more serious problem that may not be recoverable.
Dart allows you to handle specific exceptions and other exceptions differently. You can define multiple catch blocks for a single try block, each handling a different type of exception. This allows you to handle each exception in a way that is most appropriate for the type of exception.
1void main() { 2 try { 3 var res = 12 ~/ 0; 4 print("The result is $res"); 5 } on IntegerDivisionByZeroException { 6 print("Cannot divide by zero"); 7 } catch (e) { 8 print("Unknown exception: $e"); 9 } 10}
The catch clause in Dart is used to catch and handle exceptions that are thrown within the try block. The catch clause can catch all types of exceptions or specific exceptions, depending on how it's defined. If a specific exception type is defined in the catch clause, only exceptions of that type will be caught. The catch clause is a crucial part of the exception-handling mechanism in Dart.
Understanding and handling exceptions is a crucial part of programming in Dart. Exceptions are anomalous conditions that occur during the execution of a program, and handling them properly ensures that your program can recover gracefully from these conditions.
Dart provides a robust exception-handling mechanism, including the try-catch block and the finally block. The try-catch block allows you to encapsulate code that might throw an exception, and handle that exception if it occurs. The finally block ensures that certain code is executed regardless of whether an exception was thrown or not.
Moreover, Dart allows you to define and throw your custom exceptions, extending the built-in exception-handling capabilities to cater to specific error conditions in your program.
By leveraging these features, you can write more robust and error-resilient Dart programs. Whether you're building a simple command-line application or a complex Flutter app, understanding how to handle exceptions will undoubtedly prove to be a valuable skill in your Dart programming journey.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.