• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wrapping an Exception  RSS feed

 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What does the following mean in Java: "wrapping an exception"?

Consider the following code: (Only the part in bold)

public static void setObjectColor( Object obj, Color color ) {
Class cls = obj.getClass();
try {
Method method = cls.getMethod( "setColor",
new Class[] {Color.class} );
method.invoke( obj, new Object[] {color} );
}

catch (NoSuchMethodException ex) {
throw new IllegalArgumentException(
cls.getName()
+ " does not support method setColor(Color)" );
}
catch (IllegalAccessException ex) {
throw new IllegalArgumentException(
"Insufficient access permissions to call"
+ "setColor(:Color) in class " + cls.getName());
}
catch (InvocationTargetException ex) {
throw new RuntimeException(ex);
}
}


The above code snippet is from : Java Reflection in Action
After this code snippet, there is a statement:
For simplicity´┐Żs sake, the code in listing 1.1 handles these exceptions by wrapping them in runtime exceptions.

I can't figure out the meaning of the above statement in the context of the aforementioned code. Please explain.
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In your example a checked exception is being caught and rethrown as an unchecked exception. "Wrapping an exception" is just this, catching one Exception and rethrowing it as another. If you write a method where you catch checked exceptions and rethrow them as unchecked exceptions, any code using this method will not have to explicity catch these exceptions.
[ July 20, 2005: Message edited by: Paul Sturrock ]
 
Kedar Dravid
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does that mean that I can call the setObjectColor method from some other method without wrapping the call to setObjectColor() in a try-catch block,
or for that matter, without providing a throws clause in the header of the method which calls setObjectColor() ?
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!