This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have constructed a simple program to test my knowledge on Exceptions using the throws statement.The main method contains the try and catch blocks ,where I have used a DivideByZeroException statement.It does not compile , complaing that it does not recognise this method.I have tried Exception & ArimeticException and both work.I have looked trough the API and cannot find DivideByZeroException even though my text book displays this.Can anyone tell me if this exists or am I being mislead.I have added the code below just in case I am missing something
an island in the sun <br />with a language of many tongue?
There's no DivideByZeroException. You probably want ArithmeticException, which is in java.lang. It only gets thrown when an integer is divided by integer zero.
Ugh, so does every integer division have to appear in a try block? No, fortunately, because ArithmeticException is a runtime exception. That means you don't need to catch it, and in fact you shouldn't. Runtime exceptions indicate conditions that are completely avoidable, so they should be dealt with by rewriting the code. In your example, if you were writing production code rather than experimental code, the presence of ArithmeticException would indicate that your code divided something by zero. Since division by zero is meaningless, the exception would indicate that part of your algorithm didn't mean anything! It's best not to ship code that doesn't mean anything.
There's an animated illustration in Chapter 11 of "Ground-Up Java" that lets you design a snippet of exception-throwing code, and then animates the exception throwing and catching mechanism.
Consultant to SCJP team.<br />Co-designer of SCJD exam.<br />Co-author of "Complete Java 2 Certification Study Guide".<br />Author of "Ground-Up Java".
Originally posted by daniel hyslop: ...I have looked trough the API and cannot find DivideByZeroException even though my text book displays this. Can anyone tell me if this exists or am I being mislead....
I do not believe there is a DivideByZeroException in the current API. However, you can define your own exceptions, and I suspect this is what your textbook is doing.
Once you have your exception defined (as a class), then you'll need to add code to the method that throws a new instance of that exception if appropriate.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
in my text book there are several examples of multiple catch blocks and it uses the DivideByZeroException as an example of a sub class of Exception but does not state it as user defined.It appears in the chapter about exceptions before we are taught about user defined Exceptions,which was probably misleading me, thanks for the help all