Exception Handling in C#
Exception handling is used to manage runtime errors gracefully and prevent application crashes.
1. try, catch, finally
- try: Contains code that may throw exceptions.
- catch: Handles exceptions.
- finally: Executes code regardless of exception occurrence (optional).
Output:
2. throw Keyword
throw is used to manually throw exceptions.
Explanation:
- Throws an exception that can be caught by
catch.
3. Creating Custom Exceptions
You can create user-defined exceptions by inheriting from Exception.
4. Common Exception Types
| Exception TypeDescription | |
NullReferenceException | Object reference is null |
IndexOutOfRangeException | Index exceeds array or collection bounds |
DivideByZeroException | Division by zero |
FormatException | Invalid format for data conversion |
OverflowException | Value exceeds limits of data type |
InvalidOperationException | Invalid operation performed on object/state |
ArgumentException | Invalid argument passed to method |
FileNotFoundException | File not found |
Example:
5. Best Practices in Exception Handling
- Catch specific exceptions first before general exceptions.
- Avoid empty catch blocks; always handle or log.
- Use finally to release resources (files, DB connections).
- Throw exceptions when necessary; avoid suppressing errors.
- Create meaningful custom exceptions for business logic.
- Do not use exceptions for control flow; use them only for exceptional cases.
Example of Proper Usage:
Summary of Chapter 8:
tryblock contains risky code.catchhandles specific exceptions.finallyexecutes always.throwmanually raises exceptions.- Custom exceptions help define business-specific errors.
- Always follow best practices to write maintainable and safe code.