Scd Chapter 6 Fall 2024.Docx (1)
Scd Chapter 6 Fall 2024.Docx (1)
Exception handling and error management are critical to building robust and resilient software
applications. It involves capturing, responding to, and managing errors (exceptional conditions)
that occur during the execution of a program to ensure that the software can continue to operate
or fail gracefully.
● An exception is an event that occurs during the execution of a program that disrupts its
normal flow.
● It is typically a runtime error that can occur due to various reasons, such as:
o Invalid input
o Network failures
o Resource unavailability
o Programming errors (e.g., division by zero)
1. Syntax Errors: Occur due to incorrect code structure, such as missing semicolons,
braces, or incorrect keywords.
2. Runtime Errors: Occur during the execution of the program. These include:
o Checked Exceptions (e.g., FileNotFoundException): Must be handled explicitly
by the programmer.
o Unchecked Exceptions (e.g., NullPointerException): Can be caught but are not
required to be handled.
3. Logical Errors: Occur when the code doesn't behave as expected, often due to incorrect
logic.
Programming languages like Java, Python, and C# provide structured mechanisms for handling
exceptions:
Example in Python:
python
Copy code
try:
# Code that may throw an exception
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
finally:
print("This will always execute.")
Example in Java:
java
Copy code
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e);
} finally {
System.out.println("This will always execute.");
}
● Catch specific exceptions rather than generic ones. This makes debugging easier and
ensures that only anticipated errors are caught.
Bad Practice:
java
Copy code
try {
// Some code
} catch (Exception e) {
// Catching a generic exception
}
Good Practice:
java
Copy code
try {
// Some code
} catch (IOException e) {
// Handling IO-specific exceptions
}
● Do not catch exceptions without proper handling or logging. This can make debugging
difficult.
Bad Practice:
python
Copy code
try:
# Some code
except Exception:
pass # Silently ignores the error
Good Practice:
python
Copy code
try:
# Some code
except ValueError as e:
print(f"ValueError: {e}") # Properly handling or logging the error
● Always use the finally block for cleanup operations (e.g., closing files, releasing
network connections).
● Throw exceptions as early as possible when a condition is detected but catch them only
where you can handle them meaningfully. This is known as the "fail fast" principle.
● Exceptions should be used for exceptional conditions, not for regular control flow.
Bad Practice:
python
Copy code
try:
result = int(input("Enter a number: "))
except:
print("That wasn't a number.") # Not ideal for normal validation
Good Practice:
python
Copy code
user_input = input("Enter a number: ")
if user_input.isdigit():
result = int(user_input)
else:
print("That wasn't a number.")
2.6. Use Custom Exceptions
● Define custom exception classes when specific scenarios arise that are not covered by
built-in exceptions. This improves readability and debugging.
java
Copy code
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
● Always document what exceptions a method can throw in your code documentation (e.g.,
Javadoc, docstrings).
Effective error monitoring and logging are essential for detecting, diagnosing, and fixing issues
in production environments.
● Logging helps in tracking the execution flow of an application and diagnosing problems.
● Logs are crucial for post-mortem analysis, especially in production environments where
direct debugging is impossible.
● Automated monitoring tools can detect errors, report them, and provide insights into their
frequency and impact.
1. Sentry: Real-time error tracking for various programming languages, providing detailed
error reports and context.
2. New Relic: Offers performance monitoring and error tracking across various services and
applications.
3. Datadog: Monitors applications, infrastructure, and logs in real-time with error reporting
features.
4. Loggly: A cloud-based log management and error tracking system that aggregates logs
from various services.
● Centralized logging solutions aggregate logs from multiple sources (servers, applications)
into one system for analysis.