Skip to content

Instantly share code, notes, and snippets.

@rshepherd
Last active October 17, 2022 07:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rshepherd/7669931 to your computer and use it in GitHub Desktop.
Save rshepherd/7669931 to your computer and use it in GitHub Desktop.
Introduction to Java exceptions
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;
public class Exceptions {
// An exception is an event that occurs during the execution of a program
// that disrupts the normal flow of instructions.
public static void main(String[] args) throws Exception {
// There are a number ways to handle errors in code.. what are the trade-offs?
// 1) Print a message and exit the program
// 2) Return a special value. (Remember sentinel values?)
// 3) Pass along an reference object that contains possible error information.
// ....enter Exceptions
// The term exception is shorthand for the phrase "exceptional event."
// It is some kind of runtime error in your code, for example...
// ..a dereference of a null pointer
Object nullObject = null;
try {
System.out.println(nullObject.toString());
} catch (NullPointerException npe) {
// can't turn null into a string.
System.out.println(npe);
}
// ..an out-of-bounds array access
int[] intArray = { 0, 1, 2 };
try {
System.out.println(intArray[3]);
} catch (ArrayIndexOutOfBoundsException aie) {
// can't reference a memory location past the end of an array.
System.out.println(aie);
}
// .. a divide by zero
try {
System.out.println(1 / 0);
} catch (ArithmeticException ae) {
// divide by zero
System.out.println(ae);
}
// The above exceptions were all cause by the programmer!
// (And you probably wouldn't catch these, as they are generally unrecoverable.)
// Alternatively these errors can be caused by a user..
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("The number entered is " + number);
} catch (InputMismatchException ex) {
System.out.println("Incorrect input: an integer is required");
}
// These are the types of exceptions you would handle.
// The structure of exception handling blocks are as follows..
// try {
// statements (including function calls) that might cause an exception
// } catch ( exception-1 id1 ) {
// code to handle the first kind of exception
// } catch ( exception-2 id2 ) {
// code to handle the second kind of exception
// } catch (Throwable t) {
// code to handle any other tyoes of exceptions
// }
// } finally {
// code that will execute whenever this *try* block does
// }
// Creating an exception object and handing it to the runtime system is called 'throwing' an exception.
// That is, the code that caused the error stops executing immediately, and control is
// transferred to the catch clause for *that* exception
try {
throwAnException();
} catch (IllegalArgumentException e) {
// Java exceptions are objects, so the statements in a catch clause can refer to the thrown
// exception object using the specified name. Name is scoped to catch block.
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// Each catch clause specifies the type of one exception, and provides a name for it
// (similar to the way a function definition specifies the type and name of parameters).
// finally & exception translation
String line = readFirstLine("imaginary-file");
System.out.println(line);
}
// Checked & Unchecked exceptions
// Every exception is either a checked exception or an unchecked exception. If a method includes code that
// could cause a checked exception to be thrown, then:
// the exception must be declared in the method header, using a throws clause, or
// the code that might cause the exception to be thrown must be inside a try block with a catch clause for that exception.
private static void throwAnException() throws Exception {
// Note that recovery is often not possible at the point of the error.
// Therefore, it is desirable to "pass the error up" to a level that can deal with it.
int r = new Random().nextInt(3);
if (r == 0) {
throw new IllegalArgumentException();
} else if (r == 1) {
throw new NullPointerException();
} else if (r == 2) {
throw new Exception();
}
}
// finally & exception translation
private static String readFirstLine(String fileName) throws IOException {
File file = new File(fileName);
Scanner fileReader = null;
try
{
fileReader = new Scanner(file);
return fileReader.nextLine();
}
catch (NullPointerException e)
{
throw new IOException("Bad filename.");
}
catch (FileNotFoundException e)
{
throw new IOException("Missing file.");
}
finally {
// This block executes regardless of what happens in the try block
if (fileReader != null) {
fileReader.close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment