Throwable and exception
Mon Jul 08 2024 16:12:41 GMT+0000 (Coordinated Universal Time)
Saved by
@projectrock
// Custom exception class extending Exception
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
// Custom error class extending Error
class CustomError extends Error {
public CustomError(String message) {
super(message);
}
}
public class ThrowableAndExceptionDemo {
public static void main(String[] args) {
try {
// Triggering custom exception
triggerCustomException();
} catch (CustomException e) {
System.out.println("Caught custom exception: " + e.getMessage());
} catch (Exception e) {
System.out.println("Caught general exception: " + e.getMessage());
}
try {
// Triggering custom error
triggerCustomError();
} catch (CustomError e) {
System.out.println("Caught custom error: " + e.getMessage());
} catch (Error e) {
System.out.println("Caught general error: " + e.getMessage());
}
System.out.println("Program completed.");
}
// Method to trigger custom exception
public static void triggerCustomException() throws CustomException {
throw new CustomException("This is a custom exception.");
}
// Method to trigger custom error
public static void triggerCustomError() {
throw new CustomError("This is a custom error.");
}
}
content_copyCOPY
Comments