Checked and unchecked exceptions: C# and Java

Both languages throw and catch, and both end an uncaught exception with a stack trace. The difference is the compiler: a C# exception is a value the methods may throw or not, and a Java method must declare the checked exceptions it throws, which is why javac refuses a program that calls such a method without a try or a declaration. The task is a parse that throws, a report that refuses a negative count, and one filter.

The task in C#

A try, a catch of the exact type, a finally, and a second catch with an exception filter that looks at the parameter name:

Console.WriteLine("exceptions 1.0"); try { Console.WriteLine($"parsed {Parse("42")}"); Console.WriteLine($"parsed {Parse("nope")}"); } catch (FormatException ex) { Console.WriteLine($"caught {ex.GetType().Name}: {ex.Message}"); } finally { Console.WriteLine("finally"); } try { Report(-1); } catch (ArgumentOutOfRangeException ex) when (ex.ParamName == "count") { Console.WriteLine($"filtered {ex.Message}"); } static int Parse(string text) => int.TryParse(text, out var value) ? value : throw new FormatException($"not a number: {text}"); static void Report(int count) { if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count), "count is negative"); } Console.WriteLine($"report {count}"); }

dotnet run
echo "status: $?"

exceptions 1.0
parsed 42
caught FormatException: not a number: nope
finally
filtered count is negative (Parameter 'count')
status: 0

The same task in Java

The same parse and the same refusal with unchecked exceptions, and one catch of each:

public class Exceptions { public static void main(String[] args) { System.out.println("exceptions 1.0"); try { System.out.println("parsed " + parseInt("42")); System.out.println("parsed " + parseInt("nope")); } catch (NumberFormatException ex) { System.out.println("caught " + ex.getClass().getSimpleName() + ": " + ex.getMessage()); } finally { System.out.println("finally"); } try { report(-1); } catch (IllegalArgumentException ex) { System.out.println("filtered " + ex.getMessage()); } } static int parseInt(String text) { try { return Integer.parseInt(text); } catch (NumberFormatException ex) { throw new NumberFormatException("not a number: " + text); } } static void report(int count) { if (count < 0) { throw new IllegalArgumentException("count is negative"); } System.out.println("report " + count); } }

javac -g -d out Exceptions.java
java -cp out Exceptions
echo "status: $?"

exceptions 1.0
parsed 42
caught NumberFormatException: not a number: nope
finally
filtered count is negative
status: 0

The checked exception

The part C# has no equivalent for. A Java method that throws IOException must say so, and the caller must catch it or declare it too. The program below declares it in the method and forgets it in the caller, and javac refuses the file:

import java.io.IOException; public class Checked { public static void main(String[] args) { read(); } static void read() throws IOException { throw new IOException("no file"); } }

javac -g -d out Checked.java
echo "status: $?"

Checked.java:5: error: unreported exception IOException; must be caught or declared to be thrown
        read();
            ^
1 error
javac status: 1

The message is the rule: must be caught or declared to be thrown. A C# program that calls a method which throws an exception compiles without a word, and the failure is a run-time one; the Java compiler makes the possibility part of the signature.

What differs

The next page is about the tools: the build file, the publish, the jar and the measured times of this container.

Exercises

  1. Add a custom exception to both programs and catch it.
  2. Move the filter condition into the Java catch body and compare what a reader sees.
  3. Declare the IOException in the caller as well and compile the checked program.
  4. Write a try-with-resources in Java and the same with using in C#.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which language has checked exceptions?

    Answer

    Java

    javac refuses the undeclared IOException; the C# compiler does not.

  2. What does the javac error say?

    Answer

    unreported exception IOException; must be caught or declared to be thrown

    That is the real message of the page.

  3. What does this program print? try { throw new FormatException("not a number: nope"); } catch (FormatException ex) { Console.WriteLine($"caught {ex.GetType().Name}: {ex.Message}"); }

    Answer

    caught FormatException: not a number: nope

    The measured C# line names the type and the message.

  4. What is an exception filter in C#?

    Answer

    A when clause on a catch that decides whether the handler runs

    The page filters on the parameter name.

  5. What does this program print? try { Console.WriteLine("try"); } finally { Console.WriteLine("finally"); }

    Answer

    finally

    A finally runs after the try whether or not it threw.

  6. What does the C# message of the negative count include?

    Answer

    The parameter name in parentheses

    The measured line is count is negative (Parameter 'count').

  7. What does this program print? try { throw new InvalidOperationException("x"); } catch (Exception ex) { Console.WriteLine(ex is InvalidOperationException); }

    Answer

    True

    An IOException is an Exception, so the catch of the base takes it.

  8. Which Java construct closes a resource on every path?

    Answer

    try-with-resources

    It is the Java counterpart of the C# using statement.

  9. What does this program print? try { Console.WriteLine("a"); throw new Exception("x"); } catch (Exception) { Console.WriteLine("b"); }

    Answer

    a

    The first line of the try runs before the exception.

  10. Why does the C# compile without a declaration of the exception?

    Answer

    C# exceptions are unchecked: no signature lists them

    The page names this as the difference from javac.

The C# program was built with the .NET SDK 10.0.303 and the Java program with OpenJDK 21.0.13.1 (javac 21.0.13.1), both run on Alpine Linux 3.24.3 (x86_64, four processors) in a Docker container.

Article author: Arthur Isaev