Windows Application - SPLessons

Win App Exception Handling

Home > Lesson > Chapter 27
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Win App Exception Handling

Windows Application Exception Handling

shape Description

Exception Handling provides a way to avoid the occurrence of the errors. To learn exception handling, one have to know that the location where there is a chance to occur an error. The Exception is an object. Exception Class is the root class for all type of exceptions. First of all, one should know the Built-in Exceptions in the .Net framework.

shape Types

There are three types of Exception Handling Mechanisms.
  1. Using try, catch, throw and finally
  2. Logical Handling
  3. User-defined Exceptions

Using try, catch, throw and finally

shape Description

This mechanism is used by many people. By using this try, catch, throw and finally blocks, one can handle errors.
  • try:  try block contains the code that may expect to cause errors.
  • catch: Raised exception will be handled in the catch block. Simply catches the exception and
  • throw: throws an exception which is raised.
  • Finally: Contains the statements which to be executed.
one can write any number of exceptions for so single try block.

shape Syntax

The below code shows you the syntax. [csharp] try { //code which may cause error } catch(ExceptionName e1) { //error handling code } catch(exceptionName e2) { //error handling code } finally { // statements finally executes } [/csharp]

Logical Handling

shape Description

In this mechanism, one can write code in the logic where that may cause an error.For example

shape Example

See the below example code. [csharp] private void Form1_Load(object sender, EventArgs e) { int a, b, Result; a = 12; b = 0; Result = a / b; //cause divide by zero error } [/csharp] To avoid this error, one can use built-in exception or logical handling, and can write the above code as below. Then the error not occurred. [csharp] private void Form1_Load(object sender, EventArgs e) { int a, b, Result; a = 12; b = 0; if(b==0) { MessageBox.Show("invalid operation"); } else { Result = a / b; } } [/csharp] It will display a user-friendly message when an error occurs.

User-defined Exceptions

shape Description

User-defined Exceptions are created by the user. Here, one can use throw keyword to raise the exception. User-defined Exceptions are also called as Application Exceptions. Application Exception is a class which contains all these type of exceptions.