Hello guys, We all know about Exceptions in a programming language. Exceptions are coding errors, Which terminates our program while it is running. To handle these type of situations we will be using Try Catch code block. It is as simple as we have seen in Cricket and Base ball, Where a player hits a ball using Bat and a fielder catches the ball to avoid making run by the bats man. This happens same in programming language when we usages Try Catch block. So in this tutorial we would learn about Example of Try Catch to Handle Exception in Dart Flutter.
Contents in this project Example of Try Catch to Handle Exception in Dart Flutter :-
There are basically 3 types of Try Catch Syntax available in Dart for exception handling.
1. Try Catch to handle Any Exception :
1 2 3 4 5 |
try { //Source Code to throw an exception } catch(e) { //Other Source Code } |
2. Try Catch to Handle Specific type of Exception :
1 2 3 4 5 |
try { //Source Code to throw an exception } on ExceptionName { //Other Code. } |
3. Try Catch to Handle Multiple type of Exceptions Together :
1 2 3 4 5 6 7 8 9 |
try { //Source Code to throw an exception. } on ExceptionOne { //Source Code } on ExceptionTwo { //Source Code } catch(e) { //Source Code } |
Now after reading above examples. You know how easy is to Handle Exception in dart. But we would not stop here. I have explained you the syntax of Try and Catch block. But without an example it is not useful for beginners So let’s make an example of in dart How to use Try Catch for handling exceptions 🙂 .
1. Try Catch Example with Simple Exception Handling :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
void showUserName(temp) { if (temp.length > 0) { print(temp); } else { throw Exception('User Name is Empty.'); } } void main() { var userName = ''; try { showUserName(userName); } catch (e) { print('Exception is Handled...'); } } |
Output :
1 |
Exception is Handled... |
Output Without Try Catch :
1 |
Uncaught Error: Exception: User Name is Empty. |
2. Try Catch Example to handle Specific Exception :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
class UserNameEmptyException implements Exception { String data; UserNameEmptyException(this.data); } void showUserName(data) { if (data.length > 0) { print(data); } else { throw UserNameEmptyException('User Name is Empty.'); } } void main() { var userName = ''; try { showUserName(userName); } on UserNameEmptyException { print('Given User Name is Empty.'); } } |
Output :
1 |
Given User Name is Empty. |
Output Without Exception Handling :
1 |
Uncaught Error: Instance of 'UserNameEmptyException' |
So now friends, You all know how it is working. If you want to test this code right not then you can use Dart’s own online Dart Pad HERE. It will allow you to run dart code directly online.