Bacancy Technology
Bacancy Technology represents the connected world, offering innovative and customer-centric information technology experiences, enabling Enterprises, Associates and the Society to Rise™.
12+
Countries where we have happy customers
1050+
Agile enabled employees
06
World wide offices
12+
Years of Experience
05
Agile Coaches
14
Certified Scrum Masters
1000+
Clients projects
1458
Happy customers
Artificial Intelligence
Machine Learning
Salesforce
Microsoft
SAP
June 19, 2024
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.
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
If you have a custom exception class, then you can use that with on keyword. Here I mentioned example of Http Exception.