C# - SPLessons

C# Exception Handling

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

C# Exception Handling

C# Exception Handling

shape Description

In C#, there are many instances where errors occuring in programming but in few exceptional cases some errors might not be caught this situation is called as Exceptions. To control this exception a technique called Exception Handling is used. C# Exception Handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures and to clean up resources afterwards.

Common Exceptions

shape Exceptions

  • System.SystemException class is the base class for all predefined system exception.
  • try block is where code is written which can throw an exception.Single try can have multiple catch Object.
  • Catch block is use to handle the exception thrown from try block.
  • Finally block is used to execute statement, which need to execute compulsory whether exception occurs or not.
  • Throws keyword catch exception when program throw an exception.

shape Conceptual figure

shape Syntax

try { //Code Here } Catch { //Code Here } Finally { //Code Here }

shape Example

[csharp] using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SPLessons { class Program { static void Main(string[] args) { try { Console.WriteLine("Welcome to SPLessons Calculator"); int a=1,b=0,c=0; c=a/b; Console.WriteLine("Divide:"+c); } catch(DivideByZeroException d) { Console.WriteLine(d.Message); } catch(Exception e) { Console.WriteLine(e.Message); } finally { Console.WriteLine("Thank you for using SPLessons"); } } } [/csharp] Output: