Exceptions and errors: Java and C++
Java divides its failures in three: checked exceptions, which a method must declare and a caller must handle; unchecked ones, which are programming errors; and errors, which are the JVM telling the program that something below it broke. C++ has one kind of exception and no declaration of what a function may throw, and both languages run the cleanup of a scope while the exception travels. This page runs the Java side and shows the C++ side.
The task
A method that needs a name and declares an IOException when it does not get one, a method that divides and throws an IllegalArgumentException, and a program that catches the first, catches the second, and then throws an AssertionError to see which catch block receives it. A finally prints, so the order of the cleanup is visible.
The Java version
import java.io.IOException;
public class Failures {
static String requireName(String text) throws IOException {
if (text.isBlank()) {
throw new IOException("empty name");
}
return text.trim();
}
static int ratio(int a, int b) {
if (b == 0) {
throw new IllegalArgumentException("division by zero");
}
return a / b;
}
public static void main(String[] args) {
try {
System.out.println("name: " + requireName(" Ada "));
} catch (IOException e) {
System.out.println("checked: " + e.getMessage());
} finally {
System.out.println("finally runs");
}
try {
requireName(" ");
} catch (IOException e) {
System.out.println("caught: " + e.getMessage());
}
try {
ratio(1, 0);
} catch (RuntimeException e) {
System.out.println("unchecked: " + e.getMessage());
}
try {
throw new AssertionError("not an exception");
} catch (Exception e) {
System.out.println("never");
} catch (Throwable t) {
System.out.println("throwable: " + t.getClass().getSimpleName());
}
}
}
javac -Xlint:all -d out Failures.java
java -cp out Failures
name: Ada
finally runs
caught: empty name
unchecked: division by zero
throwable: AssertionError
Checked, unchecked and an error
requireName declares throws IOException, so the compiler refuses a caller that does not catch it or declare it in turn. That is the checked kind: the signature is a promise about failure, and the promise is part of the type of the method. The catch in the first block is therefore not optional, and the finally runs after it, which the second line of the output shows.
ratio throws an IllegalArgumentException and declares nothing, because a RuntimeException is unchecked: the compiler accepts the throw and accepts a caller that ignores it. The distinction is not the severity of the failure but its cause: a checked exception is a condition the caller can recover from, and an unchecked one is a bug in the call.
The last block is the third kind. AssertionError extends Error, which extends Throwable but not Exception, so catch (Exception) does not see it and the last catch does. An Error is the JVM saying that the program should stop: an assertion that failed, a stack that overflowed, a class that cannot be linked. Catching one is a diagnostic tool and not a control flow.
The C++ version
C++ throws a value, catches it by reference and has no checked exceptions. The block is not compiled here, because the image has no g++; the text after it says what it prints.
#include <iostream>
#include <stdexcept>
#include <string>
class Log {
public:
explicit Log(std::string name) : name_(std::move(name)) {
std::cout << "open " << name_ << '\n';
}
~Log() {
std::cout << "close " << name_ << '\n';
}
private:
std::string name_;
};
std::string require_name(const std::string& text) {
if (text.find_first_not_of(' ') == std::string::npos) {
throw std::runtime_error("empty name");
}
return text;
}
int main() {
try {
Log log("scope");
std::cout << "name: " << require_name(" Ada ") << '\n';
require_name(" ");
} catch (const std::runtime_error& error) {
std::cout << "caught: " << error.what() << '\n';
}
}
The program would print open scope, the name, then close scope while the exception travels, and then caught: empty name. The destructor is the finally: it runs on the way out whether the block returns or throws, and no catch block had to be written for the resource. That is the strength of the C++ model and the reason its cleanup is shorter than Java's, which needs a try-with-resources or a finally.
What differs and why
A checked exception is a feature with no C++ counterpart. throws in a Java signature is checked by the compiler at every call, and a method that cannot handle the failure must declare it too, so the possibility travels up the call stack as part of the types. C++ had a version of this in throw(...) dynamic exception specifications, which were deprecated in C++11 and removed in C++20; what is left is noexcept, which promises the opposite and terminates the program when the promise breaks.
The C++ compiler therefore does not know which functions throw, and a program cannot rely on a declaration to find the callers that forgot a failure. The convention is documentation and noexcept on the functions that must not throw, such as destructors and move constructors. Java's model is more explicit and its cost is the throws clause on every layer, which is why the modern style wraps a checked exception in an unchecked one at the boundary of a library.
Cleanup is the other difference. C++ runs destructors during unwinding, so every resource that owns itself is released. Java has no destructors, and the equivalent is try-with-resources, which is explicit at the site. A Java program that opens a resource outside a try block has no mechanism that closes it during an exception, which is the memory page's lesson seen from the failure side.
The habit that breaks
The habit is to catch Exception at the top of a method, print it and return a default. It compiles, it silences the compiler about the checked exceptions, and it turns every failure into the same empty answer. A C++ programmer who never wrote a catch block for a function that cannot throw finds the Java requirement noisy and reaches for the widest catch to make it go away.
The narrower habit is to forget that catch (Exception) misses Error. A program that guards a whole request with catch (Exception) still dies on an OutOfMemoryError or a failed assertion, which is the intended behaviour and a surprise to the author. The course's exception design lesson, lesson 099, is about choosing the exception and the catch, and this page is about the difference from the C++ model.
The next page
The next page is the build: a jar with a manifest against an executable and a make rule, and what the two runtimes need before a program starts. The C++ lesson is exceptions, and the Java lesson is exceptions.
The Java program was compiled with OpenJDK 21.0.13 (javac) and run on Alpine Linux in a Docker container. The C++ program is shown and was not compiled here: the image has no g++.
Article author: Arthur Isaev