Page 1 of 1

Exception Intermediates - Throwing and Chaining Examples and Explanation of how to throw and chain Exceptions Rate Topic: -----

#1 William_Wilson  Icon User is offline

  • lost in compilation
  • member icon

Reputation: 205
  • View blog
  • Posts: 4,807
  • Joined: 23-December 05

Posted 05 January 2007 - 07:13 PM

Java Exception Handling - Throwing

Hopefully you have a grasp on why and where your Exceptions are being generated, if not please read Exception Handling - Basics.


When we as programmers write code, we like it to be reusable, and when we write a piece of code that handles a certain Exception we would like to reuse it, instead of the bad style of copying and pasting it. There are two options for this, one is used here called throwing. This can be used to pass off responcibilty to handle an Exception to a method or class which called the method that generated the Exception, or to pass it to a class from which it inherits from. We will see both examples.

By using the throw command, we can avoid using try catch blocks in many instances and simply handle the problem on our own. This requires some for thought on what the errors could be.

A simple example of dividing by zero, in a subclass:

public class exceptions{
	private static class SubClass{
		private int quotient(int numerator, int denominator){
				return(numerator / denominator);
		}
	}
	public static void main(String args[]){
		int number1=2, number2=0, result=0;
		result = quotient(number1,number2);
		System.out.print(number2 + " goes into " + number1);
		System.out.println(" this many times: " + result);
	}
}


Returns the following error:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at exceptions.quotient(exceptions.java:3)
at exceptions.main(exceptions.java:7)

Throwing takes advantage of the try catch blocks as well as the options in Exceptions:
Exception();
Exception(String s);
Exception(Throwable t);
Exception(String s, Throwable t);

A message can be passed from the culprit of the Exception and it's message displayed even though it is handled by a different method or even a different class.

public class exceptions{
	private static class SubClass{
		private int quotient(int numerator, int denominator) throws ArithmeticException{
			if(denominator == 0)
				throw new ArithmeticException("Cannot divide by zero!");
			return(numerator / denominator);
		}
	 }
	public static void main(String args[]){
		int number1=2, number2=0, result=0;
		try{
			SubClass subClass = new SubClass();
			result = subClass.quotient(number1,number2);
			System.out.print(number2 + " goes into " + number1);
			System.out.println(" this many times: " + result);
		}
		catch(Exception e){
			System.out.println(e);
		}
	}
}


The output:

Quote

java.lang.ArithmeticException: Cannot divide by zero!


Even though this message is passed from another class it is held onto and printed when the error is displayed.

A more complex set of calls:
public class exceptions{
	private static class A{
		public A() throws Exception{
			new B();
		}
	}
	private static class B{
		public B() throws Exception{
			aMethod();
		}
		public void aMethod() throws Exception{
			System.out.println("We are now in A->B->aMethod()");
			throw new Exception("An Exception in aMethod"); //error here
		}
	}
	public static void main(String args[]){
		try{
			new A();
		}
		catch(Exception e){
			System.out.println(e);
		}
	}
}


*This example merely throws the Exception to be created, here is one where the exception is generated due to bad coding:
public class exceptions{
	private static class A{
		public A() throws Exception{
			new B();
		}
	}
	private static class B{
		public B() throws Exception{
			aMethod();
		}
		public void aMethod() throws Exception{
			System.out.println("We are now in A->B->aMethod()");
			System.out.println(1/0); //error here
		}
	}
	public static void main(String args[]){
		try{
			new A();
		}
		catch(Exception e){
			System.out.println(e);
		}
	}
}


This Exception is created in the same place, but the information on what the Exception was, was passed along, this is called chaining Exceptions this is where the Exceptions are and information are passed along or thrown from one method to the next until it is finally caught. You may be familiar with the following error:

Quote

unreported exception java.lang.Exception; must be caught or declared to be thrown


This occurs when you have missed an obvious throwing of an exception in the declaration of a method, when it is known to the compiler that an Exception is likely. These are often the case with built in IO functions as many issues can arise, such as a missing or misspelled file.

With chaining understood, now the errors can be compounded and each add their peice to the ending result.
public class exceptions{
	private static class A{
		public A() throws Exception{
			try{
				new B();
			}
			catch(Exception e){
				throw new Exception(e.getMessage() + "from A ", e);
			}
		}
	}
	private static class B{
		public B() throws Exception{
			try{
				aMethod();
			}
			catch(Exception e){
				throw new Exception("from aMethodl, ", e);
			}
		}
		public void aMethod() throws Exception{
			System.out.println("We are now in A->B->aMethod()");
			System.out.println(1/0); //error here
		}
	}
	public static void main(String args[]){
		try{
			new A();
		}
		catch(Exception e){
			System.out.println(e);
			e.printStackTrace();
		}
	}
}


Output:

Quote

We are now in A->B->aMethod()
java.lang.Exception: from aMethodl, from A
java.lang.Exception: from aMethodl, from A
at exceptions$A.<init>(exceptions.java:8)
at exceptions.main(exceptions.java:28)
Caused by: java.lang.Exception: from aMethodl,
at exceptions$B.<init>(exceptions.java:18)
at exceptions$A.<init>(exceptions.java:5)
... 1 more
Caused by: java.lang.ArithmeticException: / by zero
at exceptions$B.aMethod(exceptions.java:23)
at exceptions$B.<init>(exceptions.java:15)
... 2 more


From the message displayed it is easy to see how the message java.lang.Exception: from aMethodl, from A was passed along, by generating a new Exception and adding information in each catch block before throwing it again.

*By printing the stack trace the original Exception is also discovered to be a java.lang.ArithmeticException: / by zero. All Exceptions were held on to, from the cause to the printing, since new ones were generated to pass along the information.

Is This A Good Question/Topic? 0
  • +

Page 1 of 1