• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception Handling

 
Akashh Kumarr
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a method throws checked exception then while calling such method it needs to be in a try-catch right?

Now, suppose this is a method:
void play() throws Exception {}

Now calling such a method would also require try-catch or not? If yes then why?

Thanks.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Akashh,
Welcome to CodeRanch!

Akashh Kumarr wrote:If a method throws checked exception then while calling such method it needs to be in a try-catch right?

Unless the method throws it on to the caller.

Akashh Kumarr wrote:Now calling such a method would also require try-catch or not? If yes then why?

With a checked exception, you must "handle or declare" it.

This means, I can call it in either of the following ways:



 
Akashh Kumarr
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply Jeanne.

If a class extends Exception class, then it becomes a checked exception.

void play() throws Exception
{
throw new Exception();
}

The above method is directly throwing the Exception (subclass of Throwable). So I want to know if this method should be wrapped in a try-catch while calling it? Means it will work like a checked exception?
I tried it without try-catch and it compiles successfully but has a Runtime error, which means it works like Runtime Exception?

Thanks.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 35279
384
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Akashh Kumarr wrote:I tried it without try-catch and it compiles successfully but has a Runtime error, which means it works like Runtime Exception?

No. It works like a checked exception because it is one. Some IDEs are "helpful" and run code that doesn't quite compile. But you should have a compiler error if you aren't catching the exception or declaring it to be thrown. Can you post your example code here?
 
Akashh Kumarr
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jeanne Boyarsky wrote:
Akashh Kumarr wrote:I tried it without try-catch and it compiles successfully but has a Runtime error, which means it works like Runtime Exception?

No. It works like a checked exception because it is one. Some IDEs are "helpful" and run code that doesn't quite compile. But you should have a compiler error if you aren't catching the exception or declaring it to be thrown. Can you post your example code here?


Got it now.
Yeah, it is a Checked Exception.
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic