[3195] in java-interest
Re: Better way to handle user-defined exception
daemon@ATHENA.MIT.EDU (Thomas Ball)
Thu Nov 2 21:23:12 1995
Date: Thu, 2 Nov 1995 15:52:12 -0800
From: Thomas.Ball@Eng.Sun.COM (Thomas Ball)
To: edith@pencom.com
Cc: java-interest@java.Eng.Sun.COM
> Let say if method1 calls method2 ....calls method5. I thought throwing
> an exception in method5 and have method1 or method2 to catch it will make
> method3, method4 's codes cleaner because they don't need to do anything
> special in their codes.
That's exactly right -- throw the exception where the problem is detected
(method5), and then handle the exception where it's most appropriate
(method1). You understand this better than you give yourself credit for.
The only wrinkle the new compiler adds is that the intermediate methods
need to declare that they can throw method5's exception, since they
aren't dealing with that exception in any way:
void method5(int x) throws OutOfRangeException {
if (x > 10) {
throw new OutOfRangeException("x = " + Integer.toString(x));
}
}
void method2(int x) throws OutOfRangeException {
method5(x);
}
void method1(int x) {
try {
method2(x);
} catch (OutOfRangeException e) {
System.out.println(e.toString());
}
}
If method2 doesn't declare that it throws the OutOfRangeException,
the compiler will issue a warning. This encourages proper handling
of exceptions, which (in theory) can make for better code.
Tom Ball
Java Products Group
-
This message was sent to the java-interest mailing list
Info: send 'help' to java-interest-request@java.sun.com