Top Interview Questions
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.
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:
Program Stability: It prevents abrupt termination of applications by catching and managing errors.
Error Reporting: Helps developers identify issues with informative messages or logs.
Code Clarity: Separates error-handling logic from regular program logic, making the code cleaner.
Recovery Mechanism: Allows programs to recover from certain errors or perform alternate operations when exceptions occur.
Resource Management: Ensures that resources such as files, network connections, and memory are properly released even in the presence of errors.
Exceptions can broadly be classified into two types:
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.
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.
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:
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
}
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());
}
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");
}
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.");
}
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.
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:
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.
Avoid Empty Catch Blocks:
Empty catch blocks suppress errors without addressing them, which makes debugging difficult.
// Bad practice
catch (IOException e) { }
Use Finally for Cleanup:
Always release resources in the finally block to prevent memory leaks and other resource-related issues.
Log Exceptions:
Maintain logs for exceptions to help diagnose and fix problems efficiently. Logging frameworks like Log4j (Java) or NLog (C#) are commonly used.
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.
Do Not Use Exceptions for Control Flow:
Exceptions are costly in terms of performance. Use them for error conditions, not normal control flow.
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);
}
}
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.
Nested Exceptions:
An exception may occur while handling another exception. Nested exception handling allows developers to deal with such scenarios without crashing the program.
Exception Chaining:
Exceptions can be wrapped inside other exceptions to provide additional context. This is particularly useful in multi-layered applications.
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.
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.
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.
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
Answer:
Exceptions are mainly of two types:
Checked Exceptions: Must be handled at compile-time using try-catch or throws (Java). Example: IOException.
Unchecked Exceptions: Occur at runtime and do not require explicit handling. Example: ArithmeticException, NullReferenceException.
In C#:
All exceptions are unchecked (runtime).
| 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 |
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");
}
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.");
}
| 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");
}
| Feature | Checked Exception | Unchecked Exception |
|---|---|---|
| Compile-time checking | Yes | No |
| Handling | Mandatory | Optional |
| Example | IOException, SQLException | ArithmeticException, NullPointerException |
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);
}
| Feature | Exception | RuntimeException |
|---|---|---|
| Checked/Unchecked | Checked | Unchecked |
| Compile-time handling | Required | Not required |
| Example | IOException, FileNotFoundException | NullPointerException, ArithmeticException |
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.
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");
}
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");
}
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);
}
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.
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).
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");
}
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
}
Always handle specific exceptions instead of generic Exception.
Avoid using exceptions for control flow.
Use finally to release resources.
Log exceptions for debugging purposes.
Create custom exceptions if necessary for better readability.
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());
}
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);
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
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;
}
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.
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);
Answer:
Thrown when trying to access a file that does not exist.
Example:
StreamReader sr = new StreamReader("test.txt"); // FileNotFoundException
Answer:
An IOException occurs during input/output operations like reading or writing files.
Examples:
Disk full
File in use
Network failure
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");
}
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");
}
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
}
Answer:
ApplicationException was designed for user-defined exceptions, but Microsoft does not recommend using it. Instead, directly inherit from Exception.
Answer:
Yes, but it is not recommended because it can hide the original exception.
Example:
finally
{
throw new Exception("Error in finally");
}
Answer:
The exception thrown in the finally block will override the exception thrown in the catch block.
Answer:
An exception that is not caught by any catch block is called an unhandled exception, and it causes the program to terminate.
Answer:
Global exception handling catches exceptions at the application level.
Examples:
ASP.NET: ExceptionFilter, Middleware
Console app: AppDomain.CurrentDomain.UnhandledException
Answer:
Exceptions reduce performance
Code becomes hard to read
Intended only for unexpected situations
Answer:
try block has minimal overhead
Throwing an exception is expensive
Avoid throwing exceptions frequently
Answer:
System.Exception is the base class for all exceptions.
Answer:
Yes, constructors can throw exceptions if object initialization fails.
Answer:
InnerException stores the original exception when a new exception is thrown.
Example:
catch (Exception ex)
{
throw new Exception("High level error", ex);
}
Answer:
Exception: Catches all exceptions
SystemException: Catches system-generated exceptions only
Answer:
Thrown when a method argument is null but should not be.
void Print(string name)
{
if (name == null)
throw new ArgumentNullException("name");
}
Answer:
Occurs when a method argument is outside the allowed range.
Answer:
Always catch specific exceptions first and generic exceptions last.
catch (DivideByZeroException ex)
catch (Exception ex)
Catch specific exceptions
Never swallow exceptions
Use logging
Clean up resources in finally
Use custom exceptions wisely
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
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;
}
Answer:
Thrown when the program runs out of memory.
Causes:
Infinite loops creating objects
Large arrays
Memory leaks
Note:
Usually cannot be handled safely.
Answer:
Occurs when an operation takes longer than the allowed time.
Example:
Database timeout
Network request timeout
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
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);
}
}
Answer:
FirstChance: Raised when exception occurs (before catch)
SecondChance: Occurs when exception is not handled
Answer:
Exception bubbling is the process where an exception moves up the call stack until it is handled.
Answer:
Yes, static methods can throw exceptions just like instance methods.
Answer:
Yes, but it should be avoided inside tight loops due to performance impact.
Answer:
Java has checked and unchecked exceptions
C# has only unchecked (runtime) exceptions
Answer:
Immediately terminates the application and logs the error.
Environment.FailFast("Critical error");
Answer:
Occurs during serialization or deserialization failures.
Answer:
Thrown when a thread is forcibly terminated.
Note:
Deprecated and discouraged.
Answer:
Occurs when security permissions are violated.
Answer:
Occurs when memory is accessed incorrectly.
Answer:
Thrown when a file or directory path exceeds system limits.
Answer:
catch(Exception ex) → handles all exceptions
Catch-all may hide bugs if misused
Answer:
Logging records exception details for debugging and auditing.
Answer:
A user-defined exception used to represent business rule violations.
Answer:
Sync: exceptions thrown immediately
Async: exceptions wrapped in tasks
Answer:
Exception is stored in the Task and thrown when awaited.
Answer:
Avoids capturing synchronization context to improve performance.
Answer:
Exceptions that crash the application and cannot be recovered.
Answer:
Hiding internal exceptions and exposing user-friendly messages.
Answer:
finally: manual cleanup
using: automatic cleanup
Answer:
New exception loses original context
Rethrow preserves stack trace
Answer:
Handled using:
Middleware
Exception filters
Global handlers
Answer:
Validation errors are expected
Exceptions are unexpected
Answer:
Catch specific DB exceptions
Log details
Show user-friendly message
Answer:
No, destructors should never throw exceptions.
Answer:
Used to wrap unmanaged resources safely.
Answer:
Converting low-level exceptions to business exceptions.
Answer:
No, only one finally block per try.
Answer:
Catching generic Exception everywhere
Ignoring exceptions
Logging without rethrowing
Throwing exceptions unnecessarily
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");
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) { }
}
Answer:
Multiple approaches are used:
Global Exception Middleware (Recommended)
Exception Filters
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;
}
}
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);
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);
}
Rethrow (throw;) |
New Exception |
|---|---|
| Preserves stack trace | Loses original stack trace |
| Preferred | Avoid unless needed |
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
Answer:
Used when multiple exceptions occur in parallel execution.
try
{
Task.WaitAll(tasks);
}
catch (AggregateException ex)
{
ex.Handle(e => true);
}
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) {}
}
Answer:
Exception swallowing occurs when exceptions are caught but ignored.
Bad Practice:
catch (Exception) { }
Correct Approach:
Log
Rethrow or handle meaningfully
Answer:
| Validation | Exception |
|---|---|
| Expected | Unexpected |
| User input issue | System/runtime issue |
| Should not throw | Should throw |
Answer:
Catch DB-specific exceptions
Wrap into business exceptions
Retry transient failures
catch (SqlException ex) when (ex.Number == -2)
{
// timeout retry
}
Answer:
Temporary failures like:
Network glitch
DB timeout
Solution:
Retry with exponential backoff
Use Polly library
Answer:
Use try-catch-finally
Rollback in catch
Commit only on success
try
{
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
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.
Answer:
Stop execution immediately when a critical issue occurs.
Environment.FailFast("Critical system failure");
Answer:
Don’t use exceptions for control flow
Validate inputs before operations
Use TryParse, TryGetValue
Answer:
Repository: throw data exceptions
Service: wrap into business exceptions
Controller: convert to HTTP responses
Answer:
Java enforces checked exceptions
.NET treats all exceptions as unchecked
.NET favors cleaner APIs
Answer:
| Exception | HTTP Code |
|---|---|
| ValidationException | 400 |
| UnauthorizedException | 401 |
| NotFoundException | 404 |
| BusinessException | 409 |
| SystemException | 500 |
Answer:
Preventing internal exceptions from leaking to clients.
Example:
{
"message": "Something went wrong. Please try again later."
}
Answer:
Log exceptions
Retry or move to dead-letter queue
Alert monitoring systems
Answer:
Preserves root cause of failure.
throw new ServiceException("Failed", ex);
Answer:
Yes, but it should never throw exceptions.
Always wrap risky code inside finally with try-catch.
Answer:
Circuit breaker
Retry
Fallback
Compensation logic
Answer:
Catching Exception everywhere
Logging without context
Returning exception messages to UI
Overusing custom exceptions
Answer:
Unit tests for failure cases
Mock dependencies
Assert exception types
Assert.Throws<BusinessException>(() => service.Process());
Answer:
Error handling: expected problems
Exception handling: unexpected failures
Answer:
Timeout handling
Retry
Circuit breaker
Graceful degradation
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.
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
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) |
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
throw and throw ex?Answer:
| throw | throw ex |
|---|---|
| Preserves original stack trace | Resets stack trace |
| Recommended best practice | Not recommended |
Answer:
InnerException stores the original exception when a new exception is thrown.
Importance:
Helps identify root cause
Useful for debugging and logging
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
Answer:
Retry logic is used to handle temporary failures.
Use cases:
Network issues
Database timeouts
Temporary service unavailability
Tools:
Polly library in .NET.
Answer:
Transient exceptions are temporary errors that may succeed if retried.
Examples:
Network glitches
Timeout exceptions
Service unavailable errors
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
Answer:
AggregateException represents multiple exceptions that occur during parallel or asynchronous execution.
Used in:
Task.WaitAll
Parallel loops
Answer:
Implement retry policies
Log exceptions
Use dead-letter queues
Send alerts for failures
Examples:
Hangfire, Quartz.NET, Azure WebJobs.
Answer:
Fail-fast means terminating the application immediately when a critical error occurs.
Use cases:
Corrupted application state
Startup configuration failures
Answer:
Fail-safe ensures the system continues to operate safely even after an error occurs.
Example:
If cache fails, fallback to database.
Answer:
Commit the transaction only if successful
Rollback the transaction when an exception occurs
Never commit in a catch block
Answer:
Exception shielding hides internal technical details from end users.
User receives:
Friendly message
Error code
Answer:
Set proper timeouts
Retry transient failures
Use circuit breakers
Wrap exceptions into business exceptions
Answer:
A circuit breaker stops calling a failing service after repeated exceptions.
Benefits:
Prevents cascading failures
Improves system stability
Answer:
Use standardized error responses
Log with correlation IDs
Avoid exposing stack traces
Centralized monitoring
Answer:
Write unit tests for failure scenarios
Mock dependencies
Assert exception types and messages
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