- C# Basics
- C# Home
- C# Program Structure
- C# Basic Syntax
- C# Data Types
- C# Variables
- C# Type Conversion
- C# Constants
- C# Operators
- C# Decision Making
- C# Loops
- C# Arrays
- C# Strings
- C# Methods
- C# Nullables
- C# Structure
- C# Enum
- C# Object Oriented
- C# Classes
- C# Encapsulation
- C# Inheritance
- C# Polymorphism
- C# Operator Overloading
- C# Advance
- C# Namespaces
- C# Interfaces
- C# Preprocessors
- C# Regular Expressions
- C# Exception Handling
- C# File I/O
- C# Test
- C# Online Test
- Give Online Test
- All Test List
C# Exception Handling
Handling an exception means, handling a problem occurred during the program execution. Exceptions is used to transfer program control from one part to another. Exception handling in C#, is built-upon the following four keywords:
- try - a try block in C#, used to identify a block of code for which a particular exceptions is activated. It is followed by one/more catch block(s)
- catch - a program catches an exceptions (occurred during the program execution) with an exception handler at the place in a program where you want to handle the problem.
- throw - a program throws an exception when the problem occurred, using the keyword throw
- finally - this block is used to execute a given set of statement(s), whether an exception is thrown or not.
Here is the general form to use try, catch, and finally block in C#:
try { // statements causing an exception } catch(ExceptionName en1) { // code to handle error } catch(ExceptionName en2) { // code to handle error } catch(ExceptionName en3) { // code to handle error } finally { // statement(s) to be executed }
C# Exception Handling Example
Here is an example program, tells how to handle exception in C# program:
/* C# Exception Handling - Example Program */ using System; namespace ExceptionHandlingExample { class NumberDivision { int res; NumberDivision() { res = 0; } public void division(int num1, int num2) { try { res = num1 / num2; } catch (DivideByZeroException e) { Console.WriteLine("Exception caught: {0}", e); } finally { Console.WriteLine("Result = {0}", res); } } static void Main(string[] args) { NumberDivision d = new NumberDivision(); d.division(25, 0); Console.ReadKey(); } } }
When we compile and run the above program, it will produce the following output:
Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ... Result = 0
« Previous Tutorial Next Tutorial »
Like/Share Us on Facebook 😋