Try Block: The code that might throw an exception is placed within the try block. This could be any potentially risky code that may result in an error or exception.

Catch Block: If an exception occurs within the try block, the execution flow jumps to the corresponding catch block. Here, you can handle the exception, log it, or take any necessary corrective actions. Catch blocks are where you deal with errors gracefully, ensuring your app doesn’t crash unexpectedly.

Here I mention an example of API calling.

API calling

In this example, I make a call to a login API. The API calling code is encapsulated within a try block because it has the potential to return an error. If an error is thrown during the API call, it can be handled within the catch block. In this scenario, the error message is printed, and a LoginModel is returned, since the return type of this method is Future.

If no error is encountered during the API call, the success action is executed. Within this action, I parse the response and construct a LoginModel instance. Additionally, I handle various scenarios where the status code is not 200. For instance, if a 400 status code is received, indicating invalid username and password, I provide appropriate error handling for this specific scenario.

You can also handle error using catchError(). In this we need to pass function and inside it, we take actions according to error
catch error

If you have a custom exception class, then you can use that with on keyword. Here I mentioned example of Http Exception.
Http Exemption

Support On Demand!

Flutter