• Post Reply Bookmark Topic Watch Topic
  • New Topic

Exception  RSS feed

 
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
some one please tell me

my brother wrote throw new NullPointerException("...");....is it correct or not....i think he must be write System.out.println("...")throws NullPointerException;thanks
 
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Correct" in what sense?
 
sujesh Katri
Ranch Hand
Posts: 115
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

my lecturer said we always write throw inside the method only and when we write throw in the method body then we must be write throws in the context of method heading..please tell me.
 
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sujesh Katri wrote:my brother wrote throw new NullPointerException("...");....is it correct or not....i think he must be write System.out.println("...")throws NullPointerException;thanks

He can do this because NullPointerException is an unchecked exception.
The syntax you proposed is illegal. Keyword throws belongs to a signature of a method (a method definition), not the method call.

sujesh Katri wrote:my lecturer said we always write throw inside the method only and when we write throw in the method body then we must be write throws in the context of method heading..please tell me.

That is correct except for unchecked exceptions. See this.
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is not entirely correct. Unchecked exceptions do not need to be declared via "throws". Read http://docs.oracle.com/javase/tutorial/essential/exceptions/index.html to learn what the differences between checked and unchecked exceptions are.

Also, if a checked exception is thrown and subsequently caught in the same method body, it does not need to be declared either (because it does not leave the method).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!