Results 1 to 3 of 3
Thread: Exception class
- 11-05-2009, 11:58 PM #1
Member
- Join Date
- Nov 2009
- Posts
- 20
- Rep Power
- 0
- 11-06-2009, 01:35 AM #2
for #3, there is the NumberFormatException. this is automatically thrown from the Integer, Double object wrappers for int, double
2. there isn't usually an exceptions when operations by zero, here I assume you mean divide by zero.Java Code:String strNumber = "12345sdgf"; try { double aDouble = Double.parseDouble(strNumber); } catch (NumberFormatException ex) { // the user entered something that was not parseable into a number (e.g. letters) }
what is displayed is "result: infinity"Java Code:double numerator = 4; double denominator = 0; double quotient = numerator / denominator; System.out.println("result: " + quotient);
A good general exception that I like to use for general validation of what my program expects, like my business rules, is the IllegalArgumentException. It extends RuntimeException, so that means you don't have to explicitly wrap things into a try/catch all the time.
for example, back to this divide example, i now hande a check for negative numbers, and divide by zero
Java Code:double numerator = -5; double denominator = 0; if (numerator < 0) { throw new IllegalArgumentException("numerator cannot be less than zero: " + numerator); } if (denominator <= 0) { throw new IllegalArgumentException("denominator cannot be negative or zero: " + denominator); } // in this example, because of the checking above, we would not get here, exception would be thrown instead. double quotient = numerator / denominator; System.out.println("result: " + quotient);
- 11-06-2009, 01:58 AM #3
Senior Member
- Join Date
- Mar 2009
- Posts
- 552
- Rep Power
- 5
If the above doesn't make sense to you, ignore it, but remember it - might be useful!
And if you just randomly taught yourself to program, well... you're just like me!
Similar Threads
-
Need Help with Class Cast Exception
By soxfan714 in forum New To JavaReplies: 2Last Post: 11-03-2011, 04:33 PM -
exception class
By arulmozs in forum AWT / SwingReplies: 2Last Post: 10-29-2009, 02:18 PM -
Class.forName Exception
By Moncleared in forum Advanced JavaReplies: 5Last Post: 02-21-2009, 06:08 AM -
class cast exception
By venkatallu in forum New To JavaReplies: 2Last Post: 09-02-2008, 09:50 PM -
How to create your own Exception class
By Java Tip in forum java.langReplies: 0Last Post: 04-17-2008, 07:40 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks