Now we will learn about the concept of custom exception or user defined exception in C#.net with code snippets
Let us start.
First of all it is important to note that,
- Exception handling in C#.net is based on these keywords
try, catch, throw, finally.
- Exception=>It is base class for all predefined exceptions
A few predefined exceptions are:
- DivideByZeroException,
- IndexOutOfRangeException,
- OutOfMemoryException
Let us see System.DivideByZeroException with code snippets:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CustomExceptionExampleCode {
- class Program {
- static void Main(string[] args) {
- int a = 5;
- int b = 5;
- try {
- int k = 10 / (a - b);
- } catch (DivideByZeroException e) {
- Console.WriteLine(e.Message);
- }
- Console.Read();
- }
- }
- }
The output of above program is=>
I attempted to divide by zero.
Explanation
In the above program it is going to fire an inbuilt message which is mentioned in predefined exception DivideByZeroException.
Above message is fired when user tries to attempt to divide by zero.
Now let’s see how to create our own or custom exception
A few important points need to be remembered here about creating custom exceptions-
First of all we need to derive our own class. We can say MyException class from Exception class is a base class for it.
Inside this MyException class we will be able to replace the Message of base class with our own custom message.
Let us see in detail with a code snippet,
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace CustomExceptionExampleCode {
- class MyException: Exception {
- public MyException(string Message): base(Message) {}
- public MyException() {}
- public MyException(string Message, Exception inner): base(Message, inner) {}
- }
- class Program {
- static void Main(string[] args) {
- int a = 50;
- int b = 10;
- int k = a / b;
- try {
- if (k < 10) {
- throw new MyException("value of k is less than 10");
- }
- } catch (MyException e) {
- Console.WriteLine("Caught My Exception");
- Console.WriteLine(e.Message);
- }
- Console.Read();
- }
- }
- }
The output of above program is=>
It caught my exception.
The The below line of code demonstrates how to fire our own exception
- if (k < 10) {
- throw new MyException("value of k is less than 10");
- }
And also the below line of code demonstrates how to catch our own exception and fire our own message
- catch (MyException e) {
- Console.WriteLine("Caught My Exception");
- Console.WriteLine(e.Message);
- }
Summary
We can handle our own exception handling by deriving our own class from Exception as a base class for it.