When program is executing then at runtime error may be occur due to wrong data type conversion, passing invalid connection string, permission failed while opening a file and there are lots of condition. Error which is occurred at runtime is known as exception. Exception will cause abnormal termination of program execution, if no exception handler present for a given exception, then the program terminate abnormally and stops execution with an error details. This is very bad impression on user so in that condition we use exception handling mechanism in .Net application.
Exceptions are type that all derive from System.Exception class.
Exceptions are type that all derive from System.Exception class.
C# exception handling is built upon four keywords: try, catch, finally, and throw.
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
try − A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch blocks.
catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.
finally − The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.
throw − A program throws an exception when a problem shows up. This is done using a throw keyword.
- Use the try, catch and finally blocks to handle exceptions in C#.
- The try block must be followed by a catch or finally block or both.
- A multiple catch block is allowed with different exception filters.
- The finally block must come after the try or catch block.
- The finally block will always execute irrespective of
- The finally block is appropriate place for disposing objects.
- The finally block cannot have a return or break
- Nested try-catch blocks are allowed in C#.
Click To Zoom Image-Exception Read And Write File |