GARBA.ORG
Java 2 Basics > Exceptions Index - Previous - Next

Exceptions

An exception arises when something that shouldn't occur under normal circumstances happens. For example, the user try to load a ".jpg" file but the file contents are those of a Win32 EXE file. The user might lost connection to the server because someone kicked the network hub, the user may type "0" as the divisor when running a educational math software, etc.

Using try{} and catch() {}:

Example:

	int x = (int)(Math.random()*5);
	int z[] = new int[4];
	int r = 0;
	try {
		r = 15 / x;
		z[x] = r;
	}
	catch (ArithmeticException e) {
		System.out.println("Arithmetic error: "+e);
	}
	catch (ArrayIndexOutOfBoundsException e) {
		System.out.println("Array error: "+e);
	}
	finally {
		System.out.println("Done!");
	}	

	Result if x is between 1 and 3:

		Done!

	Result if x is 0:

		Arithmetic error: java.lang.ArithmeticException: / by zero
		Done!

	Result if x is 4:

		Array error: java.lang.ArrayIndexOutOfBoundsException
		Done!

You put the code to deal with an exception that might arise during execution of the try block in a catch block. If there are multiple exception classes that might arise in the try block, then several catch blocks are allowed to handle them.

Using finally

Once execution enters the try block, the code in the finally block will definitely be executed whatever the circumstances. By looking again at the last example you will notice that the finally block is always executed, no matter if the execution of the try{} block is successful or not.

There are a very few circumstances that can prevent execution of the code in a finally block:

An exception in a finally block can also be handled via a try/catch construct.

Catching Multiple Exceptions

A more specific catch block must precede a more general one in the source. Failure to meet this ordering requirement causes a compiler error. Only one catch block, that is, the first applicable one, will be executed.

Example:

	try {

		File inputFile = new File("d:\\workbench\\test.txt");
		FileReader in = new FileReader(inputFile);
		int c;
		while ((c = in.read()) != -1) {
			System.out.print((char)c);
		}
		in.close();
		System.out.println();

	}
	catch (EOFException e) {   // More specific Exception
		System.out.println(e);
	}
	catch (IOException e) {    // More general Exception    
		System.out.println(e);
	}

If we put the catch (IOException e) block first, the compiler will complain because EOFException is a subclass of IOException and more specific Exceptions should precede more general ones.

Declaring your own Exceptions

Declaring user-defined Exceptions is easy but there are some steps that should be carefully observed.

We are going to construct an Exception mechanism for a Age-Counting software as an example. Our Exception will be called AgeException.

So, our complete Exception-test program looks like this:

	class Test {
		public static void main(String args[]) {
		
			try {
				ageCounter(250);
			}
			catch (AgeException e) {
				System.out.println();
				System.out.println(e);
			}
		}

		static void ageCounter(int age) throws AgeException {

			if (age > 200) {	
				throw new AgeException("Nobody is that old");
			}
			for (int i = 0 ; i < age ; i++) {
				System.out.print(".");
			}		
		}
	}

	class AgeException extends Throwable {
		String my_error_message;
		public AgeException() { }
		public AgeException(String s) {
			my_error_message = s;
		}
		public String getMessage() {
			return my_error_message;
		}
	}

If you want to use a more specific Exception than AgeException, you need to extend AgeException and implement the same functionality. If a method will "throw" more than a single Exception, you must declare each of the Exceptions by separating each one with a comma.

Example:

	static void ageCounter(int age) throws AgeException, IOException {}

Categories of Exceptions

	java.lang.Throwable > java.lang.Exception 
	java.lang.Throwable > java.lang.Exception > java.lang.RunTimeException
	java.lang.Throwable > java.lang.Error

The Checked Exceptions (java.lang.Exception):

They describe difficulties that arise in a correct program, typically those with the environment such as user mistakes or I/O problems. Neither of these problems indicates a programming error. The programmer must write code to handle and recover from these problems.

The Runtime Exceptions (java.lang.Error):

They typically describe program bugs. Because runtime exceptions should never arise in a correct program, you are not required to handle them.

If a Runtime Exception occurs inside a try{} block, the try block will be exited and the application will continue running. If there is a finally{} block, it will also be executed.

Errors:

Errors describe problems that are very unusual and sufficiently difficult to recover from, that you are not required to handle them.

Exceptions and Methods

A method may delegate Exception handling to its caller.

Example:

	class Care {
		public static void main(String args[]) {
			try {
				readIt("c:\\workbench\\test.txt");
			}
			catch (IOException e) {
				System.out.println(e);
			}
		}

		public static void readIt(String my_file) throws IOException {

			File inputFile = new File(my_file);
			FileReader in = new FileReader(inputFile);
			int c;

			while ((c = in.read()) != -1) {
				System.out.print((char)c);
			}
			in.close();
			System.out.println();
		}
	}

As you can see, you don't need to handle Exceptions in the readIt() method, you just need to declare that the method throws IOException so the caller can handle it.

Exceptions and Overriding

When you extend and override a method, Java insists that the new method cannot be declared as throwing checked exceptions of classes other than those that were declared by the original method.

Example:

	class Disk {
		void readFile() throws EOFException {}
	}

	class FloppyDisk extends Disk {            // ERROR !!!
		void readFile() throws IOException {}
	}

The new method may only throw the same Exception declared by the overridden method (or a subclass Exception).

Then:

	class Disk {
		void readFile() throws IOException {}
	}

	class FloppyDisk extends Disk {            // OK.
		void readFile() throws EOFException {}
	}

EOFException is a subclass of IOException, so there is no problem.


© Ernesto Garbarino Top