Interview question
What is exception chaining in Java and what does getCause() do? Java में exception chaining क्या है और getCause() क्या करता है?
Answer
Exception chaining preserves the original exception when wrapping it in a new one, using getCause() to trace back through the full chain - critical for debugging layered application errors.
class ServiceException extends Exception {
public ServiceException(String message, Throwable cause) {
super(message, cause); // links to the original cause
}
}
public void fetchUserData() throws ServiceException {
try {
// Simulating a lower-level failure
throw new java.sql.SQLException('Connection timeout');
} catch (java.sql.SQLException e) {
// Wrap in a higher-level, more meaningful exception, preserving the cause
throw new ServiceException('Failed to fetch user data', e);
}
}
public void caller() {
try {
fetchUserData();
} catch (ServiceException e) {
System.out.println('Error: ' + e.getMessage()); // Failed to fetch user data
System.out.println('Caused by: ' + e.getCause()); // java.sql.SQLException: Connection timeout
Throwable cause = e.getCause();
while (cause != null) {
System.out.println(' Chain: ' + cause);
cause = cause.getCause(); // walk the full chain if deeply nested
}
}
}
// Printing the full chain in a stack trace automatically
try {
fetchUserData();
} catch (ServiceException e) {
e.printStackTrace(); // shows 'Caused by: java.sql.SQLException...' automatically
}
// Without chaining (losing context) - AVOID this pattern:
catch (java.sql.SQLException e) {
throw new ServiceException('Failed to fetch user data', null); // cause lost!
}Exception chaining नई exception में wrap करते समय original exception को preserve करता है, getCause() से पूरी chain trace की जा सकती है - layered application errors debug करने के लिए critical है।
class ServiceException extends Exception {
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
}
public void fetchUserData() throws ServiceException {
try {
throw new java.sql.SQLException('Connection timeout');
} catch (java.sql.SQLException e) {
throw new ServiceException('Failed to fetch user data', e);
}
}
public void caller() {
try {
fetchUserData();
} catch (ServiceException e) {
System.out.println('Error: ' + e.getMessage());
System.out.println('Caused by: ' + e.getCause());
Throwable cause = e.getCause();
while (cause != null) {
System.out.println(' Chain: ' + cause);
cause = cause.getCause();
}
}
}
try {
fetchUserData();
} catch (ServiceException e) {
e.printStackTrace(); // 'Caused by:' automatically दिखाता है
}
// बिना chaining के (context खो जाता है) - avoid करें:
catch (java.sql.SQLException e) {
throw new ServiceException('Failed to fetch user data', null);
}Was this answer clear?