Exception Handling

Exception Handling

Top Interview Questions

About Exception Handling

 

Exception Handling in Programming

Exception handling is a crucial aspect of modern programming that ensures software behaves predictably in the presence of unexpected events or errors. An exception is an event that occurs during the execution of a program, disrupting its normal flow. These events could be caused by user input errors, hardware failures, missing files, network interruptions, or logical errors in code. Proper exception handling allows developers to anticipate potential problems and respond to them gracefully, ensuring robust, reliable, and maintainable applications.

Importance of Exception Handling

In real-world applications, errors are inevitable. Users may provide invalid input, network connections can fail, databases might be temporarily unavailable, or files could be corrupted. Without exception handling, such errors may cause the program to crash, leading to poor user experience and potential data loss. Exception handling provides several benefits:

  1. Program Stability: It prevents abrupt termination of applications by catching and managing errors.

  2. Error Reporting: Helps developers identify issues with informative messages or logs.

  3. Code Clarity: Separates error-handling logic from regular program logic, making the code cleaner.

  4. Recovery Mechanism: Allows programs to recover from certain errors or perform alternate operations when exceptions occur.

  5. Resource Management: Ensures that resources such as files, network connections, and memory are properly released even in the presence of errors.

Types of Exceptions

Exceptions can broadly be classified into two types:

  1. Checked Exceptions:
    These are exceptions that the compiler requires the programmer to handle explicitly. They represent conditions that are outside the program’s control but can be anticipated. Examples include IOException, SQLException, and FileNotFoundException in Java. If a checked exception is not handled, the program will not compile.

  2. Unchecked Exceptions:
    These are runtime exceptions that the compiler does not require the programmer to handle explicitly. They usually result from programming errors such as invalid input, null references, or array index out-of-bounds. Examples include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException.

Some programming languages, like C#, categorize exceptions as System.Exception objects and use runtime checking, whereas in Java, the distinction between checked and unchecked exceptions is explicit.

Exception Handling Mechanisms

Most modern programming languages provide structured constructs to handle exceptions, such as try-catch-finally blocks in Java, C#, and similar languages. The typical flow of exception handling includes:

  1. Try Block:
    This block contains the code that might throw an exception. It acts as a monitored section where the program anticipates potential errors.

    try {
        int result = 10 / 0; // This will throw ArithmeticException
    }
    
  2. Catch Block:
    If an exception occurs in the try block, the catch block catches it and executes code to handle the exception. Multiple catch blocks can handle different types of exceptions separately.

    catch (ArithmeticException e) {
        System.out.println("Cannot divide by zero: " + e.getMessage());
    }
    
  3. Finally Block:
    This block is optional and executes regardless of whether an exception occurred or not. It is often used to release resources, such as closing files or database connections.

    finally {
        System.out.println("This block always executes");
    }
    
  4. Throwing Exceptions:
    Programs can also deliberately throw exceptions using the throw keyword when certain conditions are met. This is useful for enforcing constraints or signaling error conditions in a controlled manner.

    if (age < 18) {
        throw new IllegalArgumentException("Age must be 18 or older.");
    }
    
  5. Propagation of Exceptions:
    When an exception is not handled within a method, it propagates to the calling method. This allows centralized handling of exceptions in higher layers of the program, such as the user interface layer in an application.

Best Practices in Exception Handling

Effective exception handling is both an art and a science. Poor handling can make programs fragile or mask underlying issues. Here are some best practices:

  1. Catch Only What You Can Handle:
    Avoid catching generic exceptions like Exception unless absolutely necessary. Handle specific exceptions to provide meaningful recovery or error messages.

  2. Avoid Empty Catch Blocks:
    Empty catch blocks suppress errors without addressing them, which makes debugging difficult.

    // Bad practice
    catch (IOException e) { }
    
  3. Use Finally for Cleanup:
    Always release resources in the finally block to prevent memory leaks and other resource-related issues.

  4. Log Exceptions:
    Maintain logs for exceptions to help diagnose and fix problems efficiently. Logging frameworks like Log4j (Java) or NLog (C#) are commonly used.

  5. Provide User-Friendly Messages:
    Avoid exposing raw error messages or stack traces to end users. Instead, provide informative messages that guide them toward corrective action.

  6. Do Not Use Exceptions for Control Flow:
    Exceptions are costly in terms of performance. Use them for error conditions, not normal control flow.

  7. Custom Exceptions:
    Create custom exceptions to represent application-specific error conditions. This improves code readability and maintainability.

    public class InvalidUserInputException extends Exception {
        public InvalidUserInputException(String message) {
            super(message);
        }
    }
    

Exception Handling in Different Languages

  • Java:
    Java provides robust exception handling with try-catch-finally blocks, checked and unchecked exceptions, and the ability to define custom exceptions. Java’s exception hierarchy is rooted in java.lang.Throwable, which has two main subclasses: Exception and Error. Exception is meant for recoverable conditions, while Error represents serious problems (like OutOfMemoryError) that are generally unrecoverable.

  • C#:
    C# follows a similar model with try-catch-finally. It has a unified exception hierarchy rooted in System.Exception. C# does not differentiate between checked and unchecked exceptions, simplifying exception handling at the cost of relying more on programmer discipline.

  • Python:
    Python uses try-except-finally blocks. Python treats all exceptions as runtime objects, and it is common to handle multiple exceptions in a single except block or use else for code that should run only if no exception occurs.

  • C++:
    C++ uses try-catch blocks and allows throwing objects of any type, though it is recommended to throw exceptions derived from std::exception. Resource management is often paired with RAII (Resource Acquisition Is Initialization) to ensure proper cleanup.

Advanced Concepts in Exception Handling

  1. Nested Exceptions:
    An exception may occur while handling another exception. Nested exception handling allows developers to deal with such scenarios without crashing the program.

  2. Exception Chaining:
    Exceptions can be wrapped inside other exceptions to provide additional context. This is particularly useful in multi-layered applications.

  3. Global Exception Handling:
    In large applications, it is common to define a global exception handler to catch any unhandled exceptions, log them, and provide a consistent response to users.

  4. Asynchronous Exception Handling:
    With the rise of asynchronous programming (like async/await in C# or JavaScript Promises), exceptions must be handled in a way that ensures they propagate correctly across asynchronous boundaries.

Fresher Interview Questions

 

1. What is Exception Handling?

Answer:
Exception handling is a mechanism to handle runtime errors in a program, preventing the program from crashing and allowing it to execute smoothly. It allows developers to detect, manage, and respond to exceptions that occur during program execution.

Example in C#:

try
{
    int num = 10 / 0; // This will throw DivideByZeroException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Cannot divide by zero!");
}
finally
{
    Console.WriteLine("Execution completed.");
}

Key Points:

  • try block: Code that may throw an exception.

  • catch block: Handles the exception.

  • finally block: Executes regardless of exception occurrence.


2. What is an Exception?

Answer:
An exception is an abnormal condition or error that occurs during program execution, such as dividing by zero, accessing a null object, or reading a file that doesn’t exist.

Example:

  • DivideByZeroException

  • NullReferenceException

  • FileNotFoundException


3. What are the types of exceptions?

Answer:
Exceptions are mainly of two types:

  1. Checked Exceptions: Must be handled at compile-time using try-catch or throws (Java). Example: IOException.

  2. Unchecked Exceptions: Occur at runtime and do not require explicit handling. Example: ArithmeticException, NullReferenceException.

In C#:

  • All exceptions are unchecked (runtime).


4. Difference between Error and Exception

Feature Error Exception
Definition Serious problems beyond control Abnormal conditions in program
Occurrence System level Application level
Handling Cannot be handled Can be handled
Example OutOfMemoryError DivideByZeroException

5. What is the difference between try-catch and throws?

Answer:

  • try-catch: Handles exceptions within the method.

  • throws: Declares that a method may throw an exception, leaving handling to the caller (Java only).

Example (Java):

void readFile() throws IOException {
    FileReader file = new FileReader("file.txt");
}

6. What is the finally block?

Answer:
A finally block is used to execute important code such as closing resources, regardless of whether an exception occurs or not.

Example:

try
{
    // risky code
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}
finally
{
    Console.WriteLine("Cleanup code executed.");
}

7. What is the difference between throw and throws?

Keyword Usage
throw Used to explicitly throw an exception in a method.
throws Declares exceptions that a method might throw (Java only).

Example:

void divide(int a, int b) throws ArithmeticException {
    if (b == 0)
        throw new ArithmeticException("Division by zero");
}

8. What is the difference between checked and unchecked exceptions?

Feature Checked Exception Unchecked Exception
Compile-time checking Yes No
Handling Mandatory Optional
Example IOException, SQLException ArithmeticException, NullPointerException

9. How do you create a custom exception?

Answer:
You can create a custom exception by extending the Exception class.

Example (C#):

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

try
{
    throw new MyCustomException("Custom error occurred!");
}
catch (MyCustomException ex)
{
    Console.WriteLine(ex.Message);
}

10. What is the difference between Exception and RuntimeException?

Feature Exception RuntimeException
Checked/Unchecked Checked Unchecked
Compile-time handling Required Not required
Example IOException, FileNotFoundException NullPointerException, ArithmeticException

11. What happens if an exception is not caught?

Answer:
If an exception is not caught, the program terminates abruptly, and an error message is displayed to the user. For example, a DivideByZeroException in C# will crash the program if unhandled.


12. Can we have multiple catch blocks?

Answer:
Yes, we can have multiple catch blocks to handle different types of exceptions separately.

Example:

try
{
    int[] arr = new int[5];
    arr[10] = 50; // IndexOutOfRangeException
}
catch (DivideByZeroException ex)
{
    Console.WriteLine("Divide by zero");
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Array index out of range");
}

13. Can a try block exist without a catch block?

Answer:

  • Yes, if there is a finally block.

  • No, a try block cannot exist alone.

Example:

try
{
    Console.WriteLine("Executing risky code");
}
finally
{
    Console.WriteLine("Finally block executed");
}

14. What is a nested try block?

Answer:
A try block inside another try block is called a nested try block. It allows handling exceptions at multiple levels.

Example:

try
{
    try
    {
        int num = 10 / 0;
    }
    catch (DivideByZeroException ex)
    {
        Console.WriteLine("Inner catch: " + ex.Message);
    }
}
catch (Exception ex)
{
    Console.WriteLine("Outer catch: " + ex.Message);
}

15. What is exception propagation?

Answer:
When an exception occurs in a method and is not caught there, it propagates (bubbles up) to the caller method, and this continues until it is handled. If no method handles it, the program terminates.


16. What is the difference between error and exception in .NET?

Answer:

  • Error: Represents serious problems in the environment (like StackOverflowException). Cannot usually be caught.

  • Exception: Represents conditions that a program might want to catch and handle (like DivideByZeroException).


17. How do you handle multiple exceptions in a single catch block? (C# 6+)

Answer:
You can use a single catch block with a filter:

try
{
    // risky code
}
catch (Exception ex) when (ex is DivideByZeroException || ex is NullReferenceException)
{
    Console.WriteLine("Handled multiple exceptions");
}

18. Can we rethrow an exception?

Answer:
Yes, using throw; you can rethrow the caught exception to propagate it further.

Example:

try
{
    throw new Exception("Something went wrong");
}
catch (Exception ex)
{
    Console.WriteLine("Caught exception: " + ex.Message);
    throw; // rethrow to higher level
}

19. What are some best practices for exception handling?

  1. Always handle specific exceptions instead of generic Exception.

  2. Avoid using exceptions for control flow.

  3. Use finally to release resources.

  4. Log exceptions for debugging purposes.

  5. Create custom exceptions if necessary for better readability.


20. What is the difference between try-catch-finally and using statement in C#?

Answer:

  • try-catch-finally is for exception handling.

  • using is specifically for managing resources that implement IDisposable, ensuring Dispose() is called even if an exception occurs.

using (StreamReader sr = new StreamReader("file.txt"))
{
    Console.WriteLine(sr.ReadToEnd());
}

21. What is a NullReferenceException?

Answer:
A NullReferenceException occurs when we try to access a member (method or property) of an object that is null.

Example (C#):

string name = null;
Console.WriteLine(name.Length); // NullReferenceException

How to avoid:

  • Check for null before using objects

  • Use null-conditional operator ?.

Console.WriteLine(name?.Length);

22. What is an IndexOutOfRangeException?

Answer:
This exception occurs when we try to access an array element using an invalid index (less than 0 or greater than array size).

Example:

int[] arr = {1, 2, 3};
Console.WriteLine(arr[5]); // IndexOutOfRangeException

23. What is a DivideByZeroException?

Answer:
It occurs when a number is divided by zero.

Example:

int a = 10;
int b = 0;
int result = a / b; // DivideByZeroException

Prevention:

if (b != 0)
{
    result = a / b;
}

24. What is StackOverflowException?

Answer:
This exception occurs when the stack memory is exhausted, usually due to infinite or deep recursion.

Example:

void Test()
{
    Test(); // Infinite recursion
}

Note:
This exception cannot be caught using try-catch.


25. What is FormatException?

Answer:
Occurs when input data is not in a valid format.

Example:

int num = int.Parse("ABC"); // FormatException

Safer approach:

int num;
int.TryParse("ABC", out num);

26. What is FileNotFoundException?

Answer:
Thrown when trying to access a file that does not exist.

Example:

StreamReader sr = new StreamReader("test.txt"); // FileNotFoundException

27. What is IOException?

Answer:
An IOException occurs during input/output operations like reading or writing files.

Examples:

  • Disk full

  • File in use

  • Network failure


28. Can we catch multiple exceptions using a single catch block?

Answer:
Yes, we can handle multiple exceptions in one catch block.

Example:

try
{
    // risky code
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
}

Or using filters:

catch (Exception ex) when (ex is DivideByZeroException || ex is FormatException)
{
    Console.WriteLine("Multiple exceptions handled");
}

29. What is exception filtering?

Answer:
Exception filtering allows handling exceptions based on a condition using the when keyword.

Example:

catch (Exception ex) when (ex.Message.Contains("zero"))
{
    Console.WriteLine("Exception related to zero");
}

30. What is the difference between throw and throw ex?

Answer:

throw throw ex
Preserves original stack trace Resets stack trace
Recommended Not recommended

Example:

catch (Exception ex)
{
    throw;     // Good practice
    // throw ex; // Bad practice
}

31. What is ApplicationException?

Answer:
ApplicationException was designed for user-defined exceptions, but Microsoft does not recommend using it. Instead, directly inherit from Exception.


32. Can finally block throw an exception?

Answer:
Yes, but it is not recommended because it can hide the original exception.

Example:

finally
{
    throw new Exception("Error in finally");
}

33. What happens if both catch and finally throw exceptions?

Answer:
The exception thrown in the finally block will override the exception thrown in the catch block.


34. What is unhandled exception?

Answer:
An exception that is not caught by any catch block is called an unhandled exception, and it causes the program to terminate.


35. What is global exception handling?

Answer:
Global exception handling catches exceptions at the application level.

Examples:

  • ASP.NET: ExceptionFilter, Middleware

  • Console app: AppDomain.CurrentDomain.UnhandledException


36. Why should exceptions not be used for normal program flow?

Answer:

  • Exceptions reduce performance

  • Code becomes hard to read

  • Intended only for unexpected situations


37. What is try-catch performance impact?

Answer:

  • try block has minimal overhead

  • Throwing an exception is expensive

  • Avoid throwing exceptions frequently


38. What is the base class for all exceptions in .NET?

Answer:
System.Exception is the base class for all exceptions.


39. Can constructors throw exceptions?

Answer:
Yes, constructors can throw exceptions if object initialization fails.


40. What is InnerException?

Answer:
InnerException stores the original exception when a new exception is thrown.

Example:

catch (Exception ex)
{
    throw new Exception("High level error", ex);
}

41. What is the difference between catch(Exception) and catch(SystemException)?

Answer:

  • Exception: Catches all exceptions

  • SystemException: Catches system-generated exceptions only


42. What is ArgumentNullException?

Answer:
Thrown when a method argument is null but should not be.

void Print(string name)
{
    if (name == null)
        throw new ArgumentNullException("name");
}

43. What is ArgumentOutOfRangeException?

Answer:
Occurs when a method argument is outside the allowed range.


44. What is the correct order of catch blocks?

Answer:
Always catch specific exceptions first and generic exceptions last.

catch (DivideByZeroException ex)
catch (Exception ex)

45. What are best practices for Exception Handling?

  1. Catch specific exceptions

  2. Never swallow exceptions

  3. Use logging

  4. Clean up resources in finally

  5. Use custom exceptions wisely


46. What is ArithmeticException?

Answer:
ArithmeticException occurs when an arithmetic operation fails, such as division by zero or numeric overflow.

Example:

int a = 10;
int b = 0;
int c = a / b; // ArithmeticException

47. What is InvalidCastException?

Answer:
This exception occurs when we try to convert one data type into another incompatible type.

Example:

object obj = "Hello";
int num = (int)obj; // InvalidCastException

Prevention:

int num;
if (obj is int)
{
    num = (int)obj;
}

48. What is OutOfMemoryException?

Answer:
Thrown when the program runs out of memory.

Causes:

  • Infinite loops creating objects

  • Large arrays

  • Memory leaks

Note:
Usually cannot be handled safely.


49. What is TimeoutException?

Answer:
Occurs when an operation takes longer than the allowed time.

Example:

  • Database timeout

  • Network request timeout


50. What is ObjectDisposedException?

Answer:
Thrown when we try to use an object that has already been disposed.

Example:

StreamReader sr = new StreamReader("file.txt");
sr.Dispose();
sr.ReadLine(); // ObjectDisposedException

51. What is AggregateException?

Answer:
Used mainly in parallel and asynchronous programming to wrap multiple exceptions.

Example:

try
{
    Task.WaitAll(tasks);
}
catch (AggregateException ex)
{
    foreach (var e in ex.InnerExceptions)
    {
        Console.WriteLine(e.Message);
    }
}

52. What is the difference between FirstChance, SecondChance exceptions?

Answer:

  • FirstChance: Raised when exception occurs (before catch)

  • SecondChance: Occurs when exception is not handled


53. What is exception bubbling?

Answer:
Exception bubbling is the process where an exception moves up the call stack until it is handled.


54. Can static methods throw exceptions?

Answer:
Yes, static methods can throw exceptions just like instance methods.


55. Can we use try-catch inside a loop?

Answer:
Yes, but it should be avoided inside tight loops due to performance impact.


56. What is the difference between checked exception handling in Java and C#?

Answer:

  • Java has checked and unchecked exceptions

  • C# has only unchecked (runtime) exceptions


57. What is the use of Environment.FailFast()?

Answer:
Immediately terminates the application and logs the error.

Environment.FailFast("Critical error");

58. What is SerializationException?

Answer:
Occurs during serialization or deserialization failures.


59. What is ThreadAbortException?

Answer:
Thrown when a thread is forcibly terminated.

Note:
Deprecated and discouraged.


60. What is SecurityException?

Answer:
Occurs when security permissions are violated.


61. What is AccessViolationException?

Answer:
Occurs when memory is accessed incorrectly.


62. What is PathTooLongException?

Answer:
Thrown when a file or directory path exceeds system limits.


63. What is the difference between catch and catch-all?

Answer:

  • catch(Exception ex) → handles all exceptions

  • Catch-all may hide bugs if misused


64. What is exception logging and why is it important?

Answer:
Logging records exception details for debugging and auditing.


65. What is custom business exception?

Answer:
A user-defined exception used to represent business rule violations.


66. What is the difference between synchronous and asynchronous exception handling?

Answer:

  • Sync: exceptions thrown immediately

  • Async: exceptions wrapped in tasks


67. What happens if an exception occurs in async/await?

Answer:
Exception is stored in the Task and thrown when awaited.


68. What is ConfigureAwait(false)?

Answer:
Avoids capturing synchronization context to improve performance.


69. What is fatal exception?

Answer:
Exceptions that crash the application and cannot be recovered.


70. What is exception shielding?

Answer:
Hiding internal exceptions and exposing user-friendly messages.


71. What is finally vs using for resource management?

Answer:

  • finally: manual cleanup

  • using: automatic cleanup


72. What is the difference between throw new Exception() and rethrow?

Answer:

  • New exception loses original context

  • Rethrow preserves stack trace


73. What is exception handling in Web API?

Answer:
Handled using:

  • Middleware

  • Exception filters

  • Global handlers


74. What is difference between validation errors and exceptions?

Answer:

  • Validation errors are expected

  • Exceptions are unexpected


75. What is the best way to handle database exceptions?

Answer:

  • Catch specific DB exceptions

  • Log details

  • Show user-friendly message


76. Can destructors throw exceptions?

Answer:
No, destructors should never throw exceptions.


77. What is SafeHandle?

Answer:
Used to wrap unmanaged resources safely.


78. What is exception re-mapping?

Answer:
Converting low-level exceptions to business exceptions.


79. Can we have multiple finally blocks?

Answer:
No, only one finally block per try.


80. What are common interview mistakes in exception handling?

Answer:

  • Catching generic Exception everywhere

  • Ignoring exceptions

  • Logging without rethrowing

  • Throwing exceptions unnecessarily

Experienced Interview Questions

 

1. How do you design an exception handling strategy in an enterprise application?

Answer:
In an enterprise application, exception handling should be centralized, consistent, and meaningful.

Strategy includes:

  • Global exception handling (Middleware / Filters)

  • Custom business exceptions

  • Logging with context (user, request, time)

  • User-friendly error messages

  • Avoid exposing internal details

Example (ASP.NET Core):

app.UseExceptionHandler("/error");

2. Difference between System.Exception and ApplicationException? Why avoid ApplicationException?

Answer:
ApplicationException was intended for user-defined exceptions but is now obsolete in practice.

Why avoid it:

  • No real benefit

  • Microsoft recommends inheriting directly from Exception

  • Causes unnecessary hierarchy confusion

Best Practice:

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

3. How do you handle exceptions in ASP.NET Web API?

Answer:
Multiple approaches are used:

  1. Global Exception Middleware (Recommended)

  2. Exception Filters

  3. Try-catch in controllers (last option)

Middleware Example:

public async Task Invoke(HttpContext context)
{
    try
    {
        await _next(context);
    }
    catch (Exception ex)
    {
        // log
        context.Response.StatusCode = 500;
    }
}

4. How do you log exceptions in production systems?

Answer:

  • Use structured logging (Serilog, NLog)

  • Log stack trace, inner exception, correlation ID

  • Avoid logging sensitive data

  • Use centralized log storage (ELK, Azure App Insights)

Example:

_logger.LogError(ex, "Error while processing order {OrderId}", orderId);

5. What is exception wrapping and when do you use it?

Answer:
Wrapping converts low-level exceptions into meaningful business exceptions.

Use case:

  • DAO → Service → Controller layers

Example:

catch (SqlException ex)
{
    throw new DataAccessException("Database failure", ex);
}

6. Difference between rethrowing and throwing a new exception?

Rethrow (throw;) New Exception
Preserves stack trace Loses original stack trace
Preferred Avoid unless needed

7. How do you handle exceptions in async/await?

Answer:
Exceptions are captured inside the Task and thrown when awaited.

try
{
    await service.ProcessAsync();
}
catch (Exception ex)
{
    // handle
}

Important:

  • Never ignore Task without awaiting

  • Use Task.WhenAll carefully


8. What is AggregateException and where is it used?

Answer:
Used when multiple exceptions occur in parallel execution.

try
{
    Task.WaitAll(tasks);
}
catch (AggregateException ex)
{
    ex.Handle(e => true);
}

9. How do you design custom exceptions correctly?

Answer:
A proper custom exception:

  • Inherits from Exception

  • Has constructors

  • Is serializable (optional but recommended)

public class OrderNotFoundException : Exception
{
    public OrderNotFoundException(string msg) : base(msg) {}
}

10. How do you prevent exception swallowing?

Answer:
Exception swallowing occurs when exceptions are caught but ignored.

Bad Practice:

catch (Exception) { }

Correct Approach:

  • Log

  • Rethrow or handle meaningfully


11. Difference between validation errors and exceptions?

Answer:

Validation Exception
Expected Unexpected
User input issue System/runtime issue
Should not throw Should throw

12. How do you handle database exceptions properly?

Answer:

  • Catch DB-specific exceptions

  • Wrap into business exceptions

  • Retry transient failures

catch (SqlException ex) when (ex.Number == -2)
{
    // timeout retry
}

13. What are transient exceptions and how do you handle them?

Answer:
Temporary failures like:

  • Network glitch

  • DB timeout

Solution:

  • Retry with exponential backoff

  • Use Polly library


14. How do you ensure exception safety in transactions?

Answer:

  • Use try-catch-finally

  • Rollback in catch

  • Commit only on success

try
{
    transaction.Commit();
}
catch
{
    transaction.Rollback();
    throw;
}

15. What is global exception handling vs local exception handling?

Answer:

  • Local: try-catch in method

  • Global: application-level handling

Best Practice:
Use global handling for cross-cutting concerns, local only when recovery is possible.


16. What is fail-fast principle in exception handling?

Answer:
Stop execution immediately when a critical issue occurs.

Environment.FailFast("Critical system failure");

17. How do you avoid performance issues caused by exceptions?

Answer:

  • Don’t use exceptions for control flow

  • Validate inputs before operations

  • Use TryParse, TryGetValue


18. How do you handle exceptions in multi-layer architecture?

Answer:

  • Repository: throw data exceptions

  • Service: wrap into business exceptions

  • Controller: convert to HTTP responses


19. Difference between checked exceptions (Java) and unchecked exceptions (.NET)?

Answer:

  • Java enforces checked exceptions

  • .NET treats all exceptions as unchecked

  • .NET favors cleaner APIs


20. How do you map exceptions to HTTP status codes?

Answer:

Exception HTTP Code
ValidationException 400
UnauthorizedException 401
NotFoundException 404
BusinessException 409
SystemException 500

21. What is exception shielding?

Answer:
Preventing internal exceptions from leaking to clients.

Example:

{
  "message": "Something went wrong. Please try again later."
}

22. How do you handle exceptions in background jobs?

Answer:

  • Log exceptions

  • Retry or move to dead-letter queue

  • Alert monitoring systems


23. What is InnerException and why is it important?

Answer:
Preserves root cause of failure.

throw new ServiceException("Failed", ex);

24. Can finally block fail? How do you handle it?

Answer:
Yes, but it should never throw exceptions.
Always wrap risky code inside finally with try-catch.


25. Real-time scenario: How do you handle partial failure in microservices?

Answer:

  • Circuit breaker

  • Retry

  • Fallback

  • Compensation logic


26. What are common mistakes developers with 3–4 years experience make?

Answer:

  • Catching Exception everywhere

  • Logging without context

  • Returning exception messages to UI

  • Overusing custom exceptions


27. How do you test exception handling?

Answer:

  • Unit tests for failure cases

  • Mock dependencies

  • Assert exception types

Assert.Throws<BusinessException>(() => service.Process());

28. What is the difference between error handling and exception handling?

Answer:

  • Error handling: expected problems

  • Exception handling: unexpected failures


29. How do you handle exceptions in third-party API calls?

Answer:

  • Timeout handling

  • Retry

  • Circuit breaker

  • Graceful degradation


30. What is global exception handling and why is it important?

Answer:
Global exception handling is a centralized mechanism to catch and handle unhandled exceptions at the application level.

Why it is important:

  • Avoids repetitive try-catch blocks

  • Provides consistent error responses

  • Improves maintainability

  • Ensures proper logging

Example:
Exception middleware in ASP.NET Core.


31. What is exception middleware in ASP.NET Core?

Answer:
Exception middleware intercepts all unhandled exceptions in the HTTP request pipeline and processes them in one place.

Benefits:

  • Centralized exception handling

  • Cleaner controllers

  • Easy logging and response mapping


32. How do you map exceptions to HTTP status codes?

Answer:

Exception Type HTTP Status Code
ValidationException 400 (Bad Request)
UnauthorizedAccessException 401 (Unauthorized)
ForbiddenException 403 (Forbidden)
NotFoundException 404 (Not Found)
BusinessException 409 (Conflict)
SystemException 500 (Internal Server Error)

33. What is exception wrapping?

Answer:
Exception wrapping means converting low-level technical exceptions into higher-level business exceptions.

Example:
SQL Exception → DataAccessException → ServiceException

Benefits:

  • Layer separation

  • Meaningful error messages

  • Easier debugging


34. What is the difference between throw and throw ex?

Answer:

throw throw ex
Preserves original stack trace Resets stack trace
Recommended best practice Not recommended

35. What is InnerException and why is it important?

Answer:
InnerException stores the original exception when a new exception is thrown.

Importance:

  • Helps identify root cause

  • Useful for debugging and logging


36. What is exception swallowing and why is it bad?

Answer:
Exception swallowing occurs when an exception is caught but not logged or rethrown.

Why it is bad:

  • Hides real problems

  • Makes debugging difficult

  • Leads to unpredictable behavior


37. What is retry logic and when should it be used?

Answer:
Retry logic is used to handle temporary failures.

Use cases:

  • Network issues

  • Database timeouts

  • Temporary service unavailability

Tools:
Polly library in .NET.


38. What are transient exceptions?

Answer:
Transient exceptions are temporary errors that may succeed if retried.

Examples:

  • Network glitches

  • Timeout exceptions

  • Service unavailable errors


39. How are exceptions handled in async/await?

Answer:
Exceptions in async methods are captured in the Task and thrown when the task is awaited.

Best practices:

  • Always await async calls

  • Handle exceptions using try-catch around await


40. What is AggregateException?

Answer:
AggregateException represents multiple exceptions that occur during parallel or asynchronous execution.

Used in:

  • Task.WaitAll

  • Parallel loops


41. How do you handle exceptions in background jobs?

Answer:

  • Implement retry policies

  • Log exceptions

  • Use dead-letter queues

  • Send alerts for failures

Examples:
Hangfire, Quartz.NET, Azure WebJobs.


42. What is the fail-fast principle?

Answer:
Fail-fast means terminating the application immediately when a critical error occurs.

Use cases:

  • Corrupted application state

  • Startup configuration failures


43. What is the fail-safe approach?

Answer:
Fail-safe ensures the system continues to operate safely even after an error occurs.

Example:
If cache fails, fallback to database.


44. How do you handle exceptions in database transactions?

Answer:

  • Commit the transaction only if successful

  • Rollback the transaction when an exception occurs

  • Never commit in a catch block


45. What is exception shielding?

Answer:
Exception shielding hides internal technical details from end users.

User receives:

  • Friendly message

  • Error code


46. How do you handle exceptions from third-party APIs?

Answer:

  • Set proper timeouts

  • Retry transient failures

  • Use circuit breakers

  • Wrap exceptions into business exceptions


47. What is a circuit breaker and how is it related to exceptions?

Answer:
A circuit breaker stops calling a failing service after repeated exceptions.

Benefits:

  • Prevents cascading failures

  • Improves system stability


48. How do you handle exceptions in microservices architecture?

Answer:

  • Use standardized error responses

  • Log with correlation IDs

  • Avoid exposing stack traces

  • Centralized monitoring


49. How do you test exception handling?

Answer:

  • Write unit tests for failure scenarios

  • Mock dependencies

  • Assert exception types and messages


50. What are common exception handling mistakes at 4 years experience level?

Answer:

  • Catching generic Exception everywhere

  • Losing stack trace using throw ex

  • Over-logging exceptions

  • Using exceptions for normal business flow

  • Exposing sensitive data in logs