Exceptions in Java

Objectives

Errors and Exceptions

Partial List of Errors and Exceptions in java.lang and java.io

Object
Δ
| Throwable
Δ
| Error
| Δ
| | AssertionError
| | LinkageError
| | VirtualMachineError
| | ThreadDeath
| | java.io.IOError
|
| Exception
Δ
| ClassNotFoundException
| NoSuchFieldException
| NoSuchMethodException
| RuntimeException
| Δ
| | ArithmeticException
| | ClassCastException
| | IllegalArgumentException
| | Δ
| | | IllegalThreadStateException
| | | NumberFormatException
| |
| | IndexOutOfBoundsException
| | Δ
| | | ArrayIndexOutOfBoundsException
| | | StringIndexOutOfBoundsException
| |
| | NegativeArraySizeException
| | NullPointerException
|
| java.io.IOException
Δ
| java.io.EOFException
| java.io.FileNotFoundException
| java.io.InterruptedIOException

Declaring that a Method Might Throw an Exception

Throwing an Exception

Handling an Exception

Complete Exception Handling Example

import java.io.*;

public class TestExceptions {
	public static void main(String[] args) {
		try {
			double s = addNumbers("numbers.dat");
			System.out.println(s);
		}
		catch (FileNotFoundException ex) {
			System.err.println(ex.getMessage());
		}
		catch (IOException ex) {
			System.err.println(ex.getMessage());
		}
		catch (Exception ex) {
			System.err.println(ex.getMessage());
		}
	}


	/* Reads and sums all the double numbers in a file. */
	public static double addNumbers(String filename) throws FileNotFoundException, IOException {
		File file = new File(filename);
		FileInputStream fin = new FileInputStream(file);
		DataInputStream din = new DataInputStream(fin);
		double sum = 0;
		try {
			/* This is an infinite loop because .readDouble() throws
			 * an EOFException when it has reached the end of a file. */
			while (true) {
				double d = din.readDouble();
				sum += d;
			}
		}
		catch (EOFException e) {
			/* We have reached the end of the file, which we expected
			 * to happen, so we do nothing here.  When the EOFException
			 * is thrown the read loop above will end. */
		}
		finally {
			din.close();
		}
		return sum;
	}
}

Common Mistakes


Copyright © 2010, Maia L.L.C.  All rights reserved.