-
I wish to ask one more question on Java. I want to implment some error
handling mechanisms in my assignment. Say if the result of calculation is too
long
to display within 8 digits, I would like to throw a self-defined exception for
the
error handler to catch it and display the corresponding message.
My code structure is like:
Code:
import java.*;
public class BinaryCalculator extends JApplet implements ActionListener {
:
:
public void init() {...}
public void actionPerformed(ActionEvent e) throws BinaryCalculatorException
{
try { ...
if certain_condition then throw new Overflow();
}
catch (BinaryCalculatorException err) {
if (err instanceof Overflow) {
System.out.println("Overflow");
}
}
}
}
class BinaryCalculatorException extends Exception {};
class Overflow extends BinaryCalculatorException {};
When I compile the program, the following message shows in the command prompt:
BinaryCalculator.java:19: actionPerformed(java.awt.event.ActionEvent) in
BinaryC
alculator cannot implement actionPerformed(java.awt.event.ActionEvent) in
java.a
wt.event.ActionListener; overridden method does not throw
BinaryCalculatorExcept
ion
public class BinaryCalculator extends JApplet implements ActionListener {
^
1 error
I can't root this out unless I remove the "throws
BinaryCalculatorException"
statement. This is just to declare what exceptions this method can thow. So why
not I can't write this down? What's wrong with throwing exception in overridden
method and how should I tackle this?
Thank you for your kind attention.
-
You do one of two things in exception handling:
Either declare that it throws your (Custom) Exception(s) (which you cannot do when extending a class that doesn't already throw this exception or parent exception)
or use a try/catch block.
So in your case, remove the "throws BinaryCalculatorException" part.
I asume you know this: Beyond the above, you need to remove ":", "...", import appropriate classes and instantiate your class to get to the "System.out.println("Overflow");" part.