0
0
C Sharp (C#)programming~5 mins

Why exception handling is needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Exception handling helps your program deal with unexpected problems without crashing. It keeps your program running smoothly and lets you fix errors nicely.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When connecting to the internet and the connection might fail.
When converting user input to a number that might be invalid.
When working with databases that might be temporarily unavailable.
Syntax
C Sharp (C#)
try {
    // code that might cause an error
} catch (ExceptionType e) {
    // code to handle the error
} finally {
    // code that runs no matter what
}

try block contains code that might cause an error.

catch block handles the error if it happens.

Examples
This example catches a divide by zero error and prints a message.
C Sharp (C#)
try {
    int result = 10 / 0;
} catch (DivideByZeroException e) {
    Console.WriteLine("Cannot divide by zero.");
}
This example catches an error when trying to use a null object.
C Sharp (C#)
try {
    string text = null;
    Console.WriteLine(text.Length);
} catch (NullReferenceException e) {
    Console.WriteLine("Object is null.");
}
Sample Program

This program asks the user for a number and divides 100 by it. It handles errors if the user enters zero or something that is not a number. The finally block always runs to say thank you.

C Sharp (C#)
using System;

class Program {
    static void Main() {
        try {
            Console.WriteLine("Enter a number:");
            int number = int.Parse(Console.ReadLine() ?? "0");
            int result = 100 / number;
            Console.WriteLine($"100 divided by {number} is {result}.");
        } catch (DivideByZeroException) {
            Console.WriteLine("Error: You cannot divide by zero.");
        } catch (FormatException) {
            Console.WriteLine("Error: That is not a valid number.");
        } finally {
            Console.WriteLine("Thank you for using the program.");
        }
    }
}
OutputSuccess
Important Notes

Always handle exceptions you expect to happen to keep your program friendly.

Use finally to clean up resources like files or connections.

Don't catch exceptions you can't handle properly; let them bubble up if needed.

Summary

Exception handling stops your program from crashing on errors.

It lets you show helpful messages to users when something goes wrong.

Use try, catch, and finally blocks to manage errors safely.