KEMBAR78
Exception Handling in C# | PDF | C Sharp (Programming Language) | Computer Science
0% found this document useful (0 votes)
18 views5 pages

Exception Handling in C#

The document provides an overview of exception handling in C#, detailing what exceptions are and common types such as DivideByZeroException and NullReferenceException. It outlines the syntax for handling exceptions using try, catch, and finally blocks, and discusses best practices for exception handling. Additionally, it includes real-world examples, interview questions, and skill tests related to exception handling in C#.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views5 pages

Exception Handling in C#

The document provides an overview of exception handling in C#, detailing what exceptions are and common types such as DivideByZeroException and NullReferenceException. It outlines the syntax for handling exceptions using try, catch, and finally blocks, and discusses best practices for exception handling. Additionally, it includes real-world examples, interview questions, and skill tests related to exception handling in C#.

Uploaded by

rupams2024
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Exception Handling in C#

What is an Exception?

An exception is a runtime error that disrupts the normal flow of a program. Examples
include:

Dividing by zero

File not found

Null reference

Exception Handling Syntax

try
{
// Code that may throw an exception
}
catch (ExceptionType ex)
{
// Handle exception
}
finally
{
// Cleanup code (optional)
}

Common Exception Types

Exception Type Description


DivideByZeroException Thrown when dividing by zero
NullReferenceException Accessing object that is null
IndexOutOfRangeExcep
Array index out of range
tion
FileNotFoundException File not found during file operation
Invalid type conversion (e.g., string
FormatException
to int)

Real-World Example

try
{
int[] numbers = { 1, 2, 3 };
Console.WriteLine(numbers[5]); // Error
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine("Index out of range: " + ex.Message);
}
finally
{
Console.WriteLine("Always runs (e.g., close files or connections)");
}

1
Multiple Catch Blocks

try
{
// risky code
}
catch (NullReferenceException ex)
{
Console.WriteLine("Null reference: " + ex.Message);
}
catch (Exception ex)
{
Console.WriteLine("General error: " + ex.Message);
}

Throwing Exceptions

throw new InvalidOperationException("Invalid operation");

Custom Exceptions

public class AgeException : Exception


{
public AgeException(string message) : base(message)
{
}
}
// Usage
if (age < 18)
throw new AgeException("Age must be 18 or older.");

Best Practices

 Catch only specific exceptions


 Use finally for cleanup
 Don’t swallow exceptions silently
 Log exception details
 Avoid throwing exceptions in loops

Interview Questions & Answers

1: What is the difference between throw and throw ex?


A: throw preserves the original stack trace; throw ex resets it.

2: What does the finally block do?


A: Executes whether an exception occurs or not; used for cleanup.

3: Can you catch multiple exceptions?


A: Yes, using multiple catch blocks or a single catch(Exception) for general handling.

4: What happens if an exception is not handled?


A: The application crashes and displays the error message.

2
5: Can we have a try block without catch?
A: Yes, but only if finally is present.

Skill Test

1: Predict the output:

try
{
int x = 5 / 0;
}
catch (DivideByZeroException)
{
Console.WriteLine("Can't divide by zero.");
}
finally
{
Console.WriteLine("Finally block executed.");
}

Ans: Can't divide by zero. Finally block executed.

2: Catch Order

try
{
string s = null;
Console.WriteLine(s.Length);
}
catch (Exception ex)
{
Console.WriteLine("General exception caught.");
}
catch (NullReferenceException ex)
{
Console.WriteLine("Null reference caught.");
}

What will be the output?

Ans: Compilation error – The more specific NullReferenceException must come before
the general Exception in the catch order.

3. Finally Without Exception

try
{
Console.WriteLine("Inside try block.");
}
catch (Exception)
{
Console.WriteLine("Inside catch block.");
}
finally
{
Console.WriteLine("Inside finally block.");
}

3
What is the output?

Ans:

Inside try block.


Inside finally block.

4. Custom Exception Usage

public class InvalidAgeException : Exception


{
public InvalidAgeException(string message) : base(message)
{
}
}
int age = 15;

try
{
if (age < 18)
throw new InvalidAgeException("Age must be 18+");
}
catch (InvalidAgeException ex)
{
Console.WriteLine(ex.Message);
}

What is the output?

Ans: Age must be 18+

5.Return in Try and Finally

static int Test()


{
try
{
return 1;
}
finally
{
return 2;
}
}

Console.WriteLine(Test());

What will this print?

Ans: 2 – The finally block overrides the return value from the try.

6.Unhandled Exception

try
{
int[] arr = new int[3];

4
arr[10] = 100;
}
catch (DivideByZeroException)
{
Console.WriteLine("Divide by zero error.");
}

What will happen?

Ans: Unhandled exception: IndexOutOfRangeException


– It's not caught because only DivideByZeroException is handled.

You might also like