Lesson-12-Exception Handling
Lesson-12-Exception Handling
1. Checked Exception
System.out.println(12/0); // DivisionByZeroException
3. Errors - StackOverFlowError
String t = "Hello";
for(int i=0;i<50; i++) {
t = fun(t);
}
// 2. NullPointerException
String s=null;
//System.out.println(s.length());
// String s1 = (String)o;
// 4. ArrayIndexOutOfBoundsException
String[] col = new String[3];
// System.out.println(col[3]);
}
public class InValidAgeException extends Exception{
Slide – 21
Because exceptions of type RuntimeException are unchecked, they can also be used by
developers to indicate a problem that needs to be corrected (useful during development,
not for production code).
Explanation
• Checked exceptions are enforced by the Java compiler to ensure proper error
handling.
• Java enforces that methods must either handle a checked exception (using a try-
catch block) or declare it (using the throws keyword).
• Compile-time checking helps catch errors early, leading to more reliable and
robust code.
• Method signature declarations make the code self-documenting and easier to
maintain.
• Mandatory handling encourages developers to address potential error conditions
and prevents oversight.
By enforcing these rules, Java aims to promote better programming practices and
enhance the stability and maintainability of applications.
Slide – 26
Separation of Concerns:
• ApplicationLayer: Contains the business logic. It calls the fetchData method and
handles the exception appropriately, including logging and alerting.
By rethrowing the exception, you allow the ApplicationLayer to handle the error in a way
that makes sense for the overall application, maintaining a clear separation of
responsibilities and ensuring that errors are managed appropriately at all levels of the
application.
try {
...
}
catch(Exception e) {
...
}
Answer:
Catching Exception can potentially mask programming errors and make debugging
difficult. Always prefer catching specific exceptions to ensure that you handle errors
appropriately and maintainable code.
Nested Try/Catch
Nested try-catch blocks are useful when different parts of your code need specific
exception handling, especially when dealing with multiple resources or complex
operations.