| Author |
When to use "throw" keyword
|
abalfazl hossein
Ranch Hand
Joined: Sep 06, 2007
Posts: 602
|
|
There is a zero divide , and a message shows and an exception caught.
There are exceptions fro open a file, and these are caught.
There is no need to use throw keyword. But if you have your own exception that is you write it yourself.Is it right?
When to use throw keyword?
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56152
|
|
|
Whenever you want to initiate the throwing of an exception -- it does not have to be one that you wrote.
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Seetharaman Venkatasamy
Ranch Hand
Joined: Jan 28, 2008
Posts: 5575
|
|
abalfazl hossein wrote: if you have your own exception that is you write it yourself.Is it right?
No; As Bear said, you can throw an Exception which is already in API . example
|
 |
Alex Parvan
Ranch Hand
Joined: Dec 10, 2009
Posts: 115
|
|
Let's say you have a Servlet or a Web Service (a java application running on a server) and a client that wants to use a method on that server. If something goes wrong on the server, you might want to throw an exception, your code will look like this:
Server:
Client:
It's not such a good example, but it's the only one i can come up with I hope this puts you on the right track.
|
"Quoting yourself is stupid" - Me
|
 |
abalfazl hossein
Ranch Hand
Joined: Sep 06, 2007
Posts: 602
|
|
http://www.faqs.org/docs/javap/c9/s3.html
There are times when it makes sense for a program to deliberately throw an exception. This is the case when the program discovers some sort of exceptional or error condition, but there is no reasonable way to handle the error at the point where the problem is discovered. The program can throw an exception in the hope that some other part of the program will catch and handle the exception.
http://www.ccs.neu.edu/course/com3118/EXCEPTION.html
throws
If a method is capable of causing an exception that it does not handle, it must specify this behaviour so that callers of the method can guard themselves against that exception.
type method-name(paramlist) throws exception-list
{
//…..
}
throws clause lists the types of exceptions that a method might throw.
Necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.
Why isn't Necessary for Error or RuntimeException?
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12907
|
|
Because RuntimeException and any other exceptions that subclass RuntimeException are unchecked exceptions. See Lesson: Exceptions in Sun's Java Tutorials to learn more about the difference between checked and unchecked exceptions.
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
 |
|
|
subject: When to use "throw" keyword
|
|
|