How Dart handles unexpected problems in your code.
Exception Handling means writing code to deal with exceptions, which are unexpected errors that happen while your program is running. Instead of the program crashing, you catch these exceptions and tell the program what to do next.
Exception: A problem or error that happens when the program runs, like trying to divide by zero or reading a file that doesn’t exist.
Imagine you want to open a gift box. But sometimes the box is locked. Instead of getting upset and stopping, you try to open it gently (try), and if it's locked (exception), you ask for help (catch). This way, you don’t give up and handle the problem calmly.
void main() {
try {
int result = 12 ~/ 0; // Division by zero causes an exception
print('Result: $result');
} catch (e) {
print('Oops! An error occurred: $e');
} finally {
print('This will always run, no matter what.');
}
}
Explanation:
try block tries to divide 12 by 0, which is not allowed and causes an exception.catch block catches the exception and prints an error message instead of crashing.finally block runs after that, always executing.Without exception handling, your program would stop suddenly when an error happens. This could cause a bad experience for users. With exception handling, your program can:
try, catch, and finally blocks to control what happens during errors.