Built-in Exceptions in C#


Exceptions are a problem that arises when a program executed. The following keyword handles exceptions in C#:

try

A try block identifies a block of code for which particular exceptions is activated.

Catch

The catch keyword indicates the catching of an exception.

finally

Execute a given set of statements, whether an exception is thrown or not thrown.

throw

An exception is thrown when a problem shows up in a program.

Example

Let us see an example to handle the error in a C# program −

Live Demo

using System;
namespace MyErrorHandlingApplication {
   class DivNumbers {
      int result;
      DivNumbers() {
         result = 0;
      }
      public void myDivision(int num1, int num2) {
         try {
            result = num1 / num2;
         } catch (DivideByZeroException e) {
            Console.WriteLine("Exception Caught: {0}", e);
         } finally {
            Console.WriteLine("Result: {0}", result);
         }
      }
      static void Main(string[] args) {
         DivNumbers d = new DivNumbers();
         d.myDivision(5, 0);
         Console.ReadKey();
      }
   }
}

Output

Result: 0

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 19-Jun-2020

292 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements