In C# we can handle custom errors by creating a CustomException class Which should be inherited by Exception class. Once the Custom Exception class is ready then in each code use try and catch block. In catch block throw a new exception for you CustomException class. In CustomException class we can write any code or logging information.
here is the Code snippet for Handling Custom Exception.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ErrorHandling;
namespace ExceptionHandling
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
int a =GetValue();
}
catch (CustomException ex)
{
MessageBox.Show(ex.Message);
}
}
private int GetValue()
{
try
{
int a = 0;
int b = 4;
int z = (b / a);
return z;
}
catch (Exception ex)
{
throw new CustomException("Devide by zero is a custom Message");
}
}
}
}
namespace ErrorHandling
{
[global::System.Serializable]
public class CustomException : Exception
{
//
// For guidelines regarding the creation of new exception types, see
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
// and
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
//
public CustomException() { }
public CustomException(string message) : base(message) { }
public CustomException(string message, Exception inner) : base(message, inner) { }
protected CustomException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context) { }
}
}
Because we can not handle the custom Error at first level of handling. So this is work around of that. If any body find any such kind of option please add the comment in this article.