General Exception in Java
I am looking to throw a general Exception
in Java.
The "situation" is basically if an empty line is encountered, an exception is thrown and the blank line ignored.
Now, I come from a C# background so I would just throw a normal Exception
. In Java, is there one? I can't seem to find it.
开发者_高级运维I know I could assert, but would this solve the problem correctly using an AssertionException
?
Thanks,
Kyle
EDIT:
Thanks for the answers. Unfortunately it was my own foolishness that allowed me to miss Exception
, which I found just before checking back. I accepted Bills answer for the assertion comment, considering I couldn't delete the question due to too many up votes (in like 10 seconds I might add, hehe).
Java has a normal Exception class, but you almost never want to throw it. I prefer to extend it (or another exception type) to make a more specific exception to throw for your specific situation.
Also, you shouldn't use assertions in place of throwing exceptions in your code. Assertions may be disabled (and are disabled by default) so you can't count on them being there when your code is run by the end user. There's a lot of good information in Sun's article Programming With Assertions.
I'm wondering why you would need to throw an exception in the first place. If your goal is to ignore blank lines, then an if
statement sounds like a better solution. Don't use exceptions as a substitute for normal flow control.
Bozho is right. But the more complete answer is that in C# all exceptions must inherit from System.Exception, whereas in Java you can throw anything that inherits from java.lang.Throwable. java.lang.Exception inherits java.lang.Throwable, and is the superclass of most exceptions used in Java. You may alternatively want to throw a java.lang.Error instead, though, or create your own throwable class to use.
Otherwise, the semantics are very similar:
throw new Exception();
However, most of the time Exceptions should be thrown only for special cases. If you expect to receive blank lines, and expect to ignore them, your code should handle this case without throwing an exception.
精彩评论