Exception Handling in C sharp Arabic #39
Suggested Videos
Multicast Delegates in C sharp Arabic #38
❑ The basics of exception handling.
Exception Handling
An exception is an unforeseen error that occurs when a program is running.
Examples: Trying to read from a file does not exist, throws FileNotFoundException. Trying to read from a database table that does not exist, Throws a SqlException.
Showing actual unhandled exceptions to the end user is bad for two reasons
1- Users will be annoyed as they are cryptic and does not make much sense to the end users.
2- Exceptions contain information , that can be used for hacking into your application.
An exception is actually a class that derivers from system .Exception class . The System. Exception class has several useful properties, that provide valuable information about the exception.
Message : Gets a message that describes the current exception. Stack Trace: Provides the call stack to the line number in the method where the exception occurred.
Releasing System Resources
We use try ,catch and finally blocks for exception handling:
Try-The code that can possibly cause an exception will be in the try block.
Catch-Handles the exception.
Finally-Clean and free resources that the class was holding onto during the program execution . Finally block is optional .
Note: it is a good practice to always release resources in the finally block, Because finally block is guaranteed to execute , irrespective of whether there is an exception or not .
Specific exceptions will be caught before the base general exception , so specific exception blocks should always be on top of the base exception block. Otherwise , you will encounter a compiler error.
Tags:
C sharp