Chapter 11: Problem 19
If you are writing a custom exception class, how can you make sure it is checked? How can you make sure it is unchecked?
Short Answer
Expert verified
In Java, the main difference between creating a custom checked exception class and a custom unchecked exception class is the inheritance hierarchy. To create a custom checked exception, you extend the `java.lang.Exception` class which will be checked at compile-time. To create a custom unchecked exception, you extend the `java.lang.RuntimeException` class which will be checked at runtime.
Example usage of a custom checked exception:
```java
public class CustomCheckedException extends Exception {
public CustomCheckedException(String message) {
super(message);
}
}
public void exampleMethod() throws CustomCheckedException {
if (someCondition) {
throw new CustomCheckedException("This is a custom checked exception");
}
}
```
Example usage of a custom unchecked exception:
```java
public class CustomUncheckedException extends RuntimeException {
public CustomUncheckedException(String message) {
super(message);
}
}
public void exampleMethod() {
if (someCondition) {
throw new CustomUncheckedException("This is a custom unchecked exception");
}
}
```
Checked exceptions require handling (via try-catch block) or declaration (via throws clause), while unchecked exceptions do not have this requirement.