C# Exception Handling

Exception handling is a vital feature in C# that enables developers to handle unexpected or exceptional situations that may arise during program execution. These exceptions can be generated by the common language runtime (CLR), the .NET Framework, third-party libraries, or application code.

Try, catch, and finally

In C#, exception handling is achieved using the try, catch, and finally keywords. The try block contains the code that may potentially throw an exception. The catch block is used to handle and process specific types of exceptions that may occur within the try block. The finally block is optional and is used to specify code that should always execute, regardless of whether an exception was thrown or not.

try { 'your code block } catch (Exception) { 'exception handling block } finally { 'final cleanup block }

Exceptions are objects that encapsulate information about irregular circumstances encountered during program execution. These circumstances can include scenarios such as running out of memory, being unable to open a file, or encountering an illegal cast.

System.Exception

C# provides built-in exception classes, such as System.Exception and its derived classes, to represent different types of exceptions. Additionally, developers can create their own customized exception classes that cater to the specific needs of their applications. This allows for more meaningful and precise exception handling, as well as providing a way to communicate specific error conditions to the caller or user.

The following C# program shows, how to create a custom exception class and how it is using in the program.

Full Source C#
using System; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { try { int i = 0; int j = 0; int k = 0; j = 10; k = 0; i = j / k; } catch (Exception ex) { throw (new MyCustomException("You cannot divide a number by zeo")); } } } public class MyCustomException : System.ApplicationException { public MyCustomException(string message) : base(message) { MessageBox.Show (message); } } }

To handle exceptions, developers can use the catch block to catch specific types of exceptions and perform appropriate error handling or recovery operations. The catch block specifies the exception type to catch and the actions to take when that exception occurs. Multiple catch blocks can be used to handle different types of exceptions or to provide specific error handling logic for each exception type.

Conclusion

Effectively utilizing exception handling in C#, developers can handle errors, recover from exceptional situations, and ensure proper resource cleanup. Customized exceptions provide additional flexibility to handle application-specific error conditions, enhancing the robustness and reliability of the code.