Java provides a way for methods to indicate when they cannot complete normally through an exception-handling mechanism.

Exceptions are objects of a type that is a subtype of Throwable. Throwing an exception causes the control flow of the executing code to jump to a point where the exception can be handled, unwinding the call stack as it goes.

To handle an exception, it is necessary to declare a try block with one or more catch clauses. A catch clause declares a variable with a type that is an exception. Any exception object propagated to the try block that can be assigned to the variable in a catch clause is caught by this clause.

/**
 * Copyright (C) 2024 by Martin Robillard. 
 * See https://codesample.info/about.html
 */
package essentials;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class ExceptionHandling
{
	public static void main(String[] args)
	{
		try
		{
			throwsChecked();
		}
catch (NullPointerException nullPointerException) { nullPointerException.printStackTrace(); }
catch (IOException ioException) { System.out.println("Caught an IOException with message: " + ioException.getMessage()); }
finally { System.out.println("This code always executes"); }
throwsUnchecked();
/* * The code below will not execute because the call to throwsUnchecked() * results in an exception propagating out of the main method. To try * our the method, you can switch the calls throwsUnchecked() and * throwsExplicit(null); */ throwsExplicit(null); } /* * This method throws an unchecked (runtime) exception of type * NumberFormatException. */ public static void throwsUnchecked() {
Integer.parseInt("Not a number");
} /* * This method throws a checked exception. */ public static void throwsChecked() throws IOException { Files.getLastModifiedTime(Path.of("NONEXISTENT FILE")); } /* * This method explicitly throws an IllegalStateException */ public static void throwsExplicit(String message) { if( message == null ) { throw new IllegalArgumentException("Message cannot be null"); } System.out.println(message); } }