Tool for HR, Hiring Managers, and the Leadership Team

Exception Handling — Interview Guide

Exception Handling is one of the most frequently asked interview topics — especially for C#, Java, .NET, and backend roles. Let's break it down in a simple, interview-focused way.


Exception Handling — Interview Guide

1. What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors so that the application doesn't crash and can continue execution gracefully.

Example Without Exception Handling

int a = 10;
int b = 0;
int result = a / b; // Crash (DivideByZeroException)

This will crash the application.

2. Basic Exception Handling Syntax

try
{
    // Risky code
}
catch (Exception ex)
{
    // Handle exception
}
finally
{
    // Always executes
}

3. Example (Most Common Interview Example)

try
{
    int a = 10;
    int b = 0;
    int result = a / b;
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero");
}
finally
{
    Console.WriteLine("Execution completed");
}

Output

Cannot divide by zero
Execution completed

4. Try, Catch, Finally Explained

Try

Contains risky code

try
{
    int x = int.Parse("abc");
}

Catch

Handles the exception

catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

Finally

Always executes (even if exception occurs or not)

finally
{
    Console.WriteLine("Cleanup code");
}

Used for:

  • Closing database connections

  • Closing files

  • Releasing memory

5. Multiple Catch Blocks (Important Interview Question)

try
{
    int[] arr = new int[2];
    arr[5] = 10;
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Index error");
}
catch (Exception ex)
{
    Console.WriteLine("General exception");
}

Important Rule

Always place:

Specific Exception → First
General Exception → Last

Wrong Order (Compile Error):

catch (Exception ex)
catch (DivideByZeroException ex)

6. Finally Block Without Catch

Yes, it's allowed.

try
{
    Console.WriteLine("Hello");
}
finally
{
    Console.WriteLine("Finally executed");
}

7. Throw Keyword

Used to manually throw exceptions

int age = 15;

if(age < 18)
{
    throw new Exception("Age must be above 18");
}

8. Throw vs Throw ex (Very Important Interview Question)

Wrong

catch(Exception ex)
{
    throw ex;
}

Correct

catch(Exception ex)
{
    throw;
}

Why?

throw; preserves original stack trace
throw ex; resets stack trace (bad for debugging)

Interview Tip:
Always use throw;

9. Custom Exception (Very Important for Senior Roles)

Create your own exception

public class AgeException : Exception
{
    public AgeException(string message) : base(message)
    {
    }
}

Use it:

if(age < 18)
{
    throw new AgeException("Invalid age");
}

10. Exception Handling Best Practices (Interview Gold)

1. Don't catch general exception unnecessarily

❌ Bad

catch(Exception ex)
{
}

✔ Good

catch(SqlException ex)
{
}

2. Don't use exceptions for normal flow

❌ Bad

try
{
    int x = int.Parse(input);
}
catch
{
}

✔ Good

int.TryParse(input, out int x);

3. Always log exceptions

catch(Exception ex)
{
    logger.LogError(ex.Message);
}

11. Common Built-in Exceptions (Interview Favorite)

Exception When It Occurs
NullReferenceException Object is null
DivideByZeroException Division by zero
IndexOutOfRangeException Invalid index
FormatException Invalid format
InvalidOperationException Invalid operation
ArgumentException Invalid argument

12. Real World Example

try
{
    using(var connection = new SqlConnection(connectionString))
    {
        connection.Open();
    }
}
catch(SqlException ex)
{
    Console.WriteLine("Database error");
}
finally
{
    Console.WriteLine("Cleanup");
}

13. Interview Tricky Questions

Q1: Can try exist without catch?

✔ Yes (with finally)

Q2: Can catch exist without try?

❌ No

Q3: Can finally exist without catch?

✔ Yes

Q4: Does finally always execute?

✔ Yes (except: Environment.FailFast, process kill)

Q5: Can we have multiple finally?

❌ No

14. Exception Handling Flow

Try → Exception Occurs → Catch → Finally

If no exception:

Try → Finally

15. Global Exception Handling (.NET Core — Very Important)

app.UseExceptionHandler("/Home/Error");

OR

Middleware

app.UseMiddleware<ExceptionMiddleware>();

16. When Should You Use Exception Handling?

Use exceptions for:

✔ Database failures
✔ API failures
✔ File access issues
✔ Unexpected errors

Don't use for:

❌ Validations
❌ Business logic
❌ Normal flow

17. Best Interview Answer (Short Definition)

Exception Handling is a mechanism to handle runtime errors in an application so that the program can continue execution gracefully without crashing.

18. Senior-Level Interview Tip

Good exception handling:

✔ Specific exceptions
✔ Logging
✔ Meaningful message
✔ No silent catch
✔ Global handling