C# Exception Handling

What is an Exception?

An exception is an error that occurs while a program is running.

If exceptions are not handled, the program will stop unexpectedly.

Loading...
Output:

Using try and catch

The try block contains code that might cause an exception.

The catch block handles the error and prevents the program from crashing.

Loading...
Output:

Handling Multiple Exceptions

You can use multiple catch blocks to handle different types of errors.

This allows more specific and helpful error handling.

Loading...
Output:

The finally Block

The finally block always runs, whether an exception occurs or not.

It is commonly used to clean up resources like closing files or database connections.

Loading...
Output:

Using throw

The throw keyword allows you to manually create an exception.

This is useful for enforcing rules in your program.

Loading...
Output:

Common Exceptions

C# has many built-in exception types to handle different errors.

  • DivideByZeroException: dividing by zero
  • NullReferenceException: using a null object
  • IndexOutOfRangeException: invalid array index
  • FormatException: invalid input format

Why Use Exception Handling?

Exception handling improves program stability and user experience.

  • Prevents crashes
  • Provides meaningful error messages
  • Allows recovery from errors

Real-World Example

Handling user input safely is a common real-world use case.

Loading...
Output:

Practice

Create a program that asks for two numbers and divides them safely using exception handling.

Loading...
Output:

Need Help?