CKTIS / Java
Exception — the base exception class
java.lang.Exception represents conditions an application may want to handle. Learn the distinction between checked and unchecked exceptions and the roles of throw, throws, and catch.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
public class Exception extends Throwable
new Exception()
new Exception(String message)
new Exception(String message, Throwable cause)
new Exception(Throwable cause)
throw new Exception("message");
void operation() throws Exception { /* ... */ }
try { operation(); } catch (Exception e) { /* ... */ }java.lang.Exception extends Throwable and describes conditions an application may want to handle. Exception is a checked exception, as are its subclasses outside the RuntimeException branch. RuntimeException itself and its subclasses are unchecked.
If the compiler determines that a checked exception can escape a method or constructor body, its type must be covered by a throws declaration. However, if the finally block associated with a try cannot complete normally, the compiler does not treat the original exception thrown in the try block as escaping the try statement. That throw therefore does not require the original exception to be caught or declared. throw actually throws an exception; throws only declares that it may propagate. Throwing an exception interrupts the current execution path, skipping the remaining statements on that path. A matching catch block runs only if the exception reaches it. If no handler matches, no catch block runs for that exception. If an intervening finally block completes abruptly, for example by throwing another exception, it can stop the original exception from propagating further. catch (Exception e) also covers RuntimeException, but not Error, which is a separate subclass of Throwable.
new Exception("message") stores a message available through the inherited getMessage(). new Exception("message", cause) also preserves a cause available through getCause(); the cause's message is not automatically appended. In production code, prefer specific exception types and do not silently discard exceptions without deliberate handling.
The example deliberately uses the general Exception type to demonstrate it. checkScore(-1) throws, so Accepted is not printed. The catch block prints Score must be non-negative.
Examples
public class Main {
static void checkScore(int score) throws Exception {
if (score < 0) {
throw new Exception("Score must be non-negative");
}
}
public static void main(String[] args) {
try {
checkScore(-1);
System.out.println("Accepted");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}Result
Score must be non-negative
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.