Throw and Throws
I am learning Exception Handling in Java and stuck with Throw and Throws
As I am not getting when to use throw and when to use throws.
17 Replies
⌛
This post has been reserved for your question.
Hey @Dev Gupta! Please useTIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here./close
or theClose Post
button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
Help Please
throw is used when you want to throw an exception
for example
throws is used when a method throws a checked exception so you gotta either use try catch or the throws thing
like this
if you use try catch you dont need the throws in the method
because the exception is handled within that try catch
or try with resources
Ok let me do it once and get clear
@ayylmao123xdd can you give example for second code
try catch or throws
try catch
ok but in like 1h or 2 cuz now im doing some stuff
Ok
Check is this correct or the other one for throw keyword
Or is this correct for the throw keyword?
this one is good yea
this one also works but you could just do like this
because you are printing it anyway
and with try catch
let me write it now
This how be use throw keyword?
and then you dont need the throws
yes
Ok, thank you for clearing the concept
heres a gif for u
l0l
and u should try with other examples too
so you remember how to do it
Ok
Maybe the following is simple and explains it (if there are any doubts left):
- These are different keywords and you cannot use one instead of the other (or you'll get a compiler error)
-
throw
is for the act of throwing an exception
- throws
makes a statement that a method might be throwing an (uncaught) exception. Calling another method that might throw an exception without catching it constitutes as such.
and you should catch exceptions wherever you feel it's sensible to handle the situation of these exceptions occuring
and you always have the option of catching an exception and throwing another one if you want to change the type of the exception💤
Post marked as dormant
This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping
.
Warning: abusing this will result in moderative actions taken against you.