— Dart, Exceptions, Error Handling — 2 min read
Exception handling is an important aspect of any programming language that allows developers to handle runtime errors gracefully. In Dart, exceptions are objects that represent different types of errors that occur during the execution of a program. However, sometimes the built-in exceptions may not be enough to handle all possible error scenarios. In such cases, you can create your own custom exceptions.
Creating custom exceptions in Dart is easy and requires only a few steps:
To create a custom exception in Dart, you need to define a new class that extends the Exception
class or any of its subclasses, such as Error
or RuntimeException
. Here's an example of how to create a custom exception class named MyException
:
1class MyException implements Exception {2 final String message;3
4 const MyException(this.message);5
6 @override7 String toString() => message;8}
In the above code, we defined a new class called MyException
that extends the Exception
class. We also defined a constructor that takes a message string as a parameter and assigned it to the message
property. Finally, we overrode the toString()
method to return the message string.
Once you have defined your custom exception class, you can throw it like any other exception by using the throw
keyword. Here's an example of how to throw the MyException
exception:
1void someFunction() {2 // ...3 throw MyException('Something went wrong!');4}
In the above code, we threw the MyException
exception with a message string that describes the error.
To catch a custom exception, you can use a try-catch
block just like you would for any other exception. Here's an example of how to catch the MyException
exception:
1try {2 someFunction();3} on MyException catch (e) {4 print(e);5}
In the above code, we caught the MyException
exception and printed its message using the print()
statement.
That's it! With these three simple steps, you can create your own custom exceptions in Dart.
Let's look at an example usage scenario where custom exceptions can be useful. Suppose you are building a mobile application that retrieves data from a remote server. If the network connection is slow or unavailable, an exception may occur. In this case, you can define a custom exception called NetworkException
to handle this scenario.
Here's an example of how to define the NetworkException
exception:
1class NetworkException implements Exception {2 final String message;3
4 const NetworkException(this.message);5
6 @override7 String toString() => message;8}
You can then use this exception class to handle network-related errors in your code. Here's an example of how to throw and catch the NetworkException
exception:
1Future<void> fetchData() async {2 try {3 final response = await http.get(Uri.parse('https://example.com/data'));4 if (response.statusCode == 200) {5 // process data here6 } else {7 throw NetworkException('Failed to fetch data: ${response.statusCode}');8 }9 } catch (e) {10 if (e is NetworkException) {11 print(e);12 // show error message to user13 } else {14 // handle other exceptions15 }16 }17}
In the above code, we defined a function called fetchData()
that makes an HTTP request to retrieve data from a remote server. If the response status code is not 200, we threw a NetworkException
exception with a message string that describes the error. We then caught the exception and checked if it was an instance of NetworkException
. If it was, we printed its message and showed an error message to the user.
Custom exceptions can help you handle errors more efficiently and effectively in your Dart projects. By defining your own exception classes, you can provide more detailed information about the error and improve the overall reliability of your code.