PDA

View Full Version : Java: When To Use Try Catch?


dealmaker
10-28-2005, 02:52 AM
Hi,
I am new in Java, and I want to know when should I use try and catch statement. I have no idea of knowing whether some code has the ability to throw exceptions. So how do I decide when to use them and when not to use them?

Many thanks.

suryad
10-28-2005, 06:40 AM
Well the API documentation when using the methods will let you know if you need a try catch block. And often times the compiler will as well if you dont use a try catch block when you need to.

dealmaker
10-28-2005, 07:09 AM
I rarely see api documentation mentions anything about using try catch block. Actually, almost never.

Well the API documentation when using the methods will let you know if you need a try catch block. And often times the compiler will as well if you dont use a try catch block when you need to.

tsclan
10-28-2005, 09:35 AM
The only time I have used try and catch is for handling files where is the file is not found instead of printing some technical error message you can get it to simply say File not found.

brad211987
10-28-2005, 05:45 PM
Straight from textbook:

"The try{}Catch{} structure should be used when it is possible that your method will fail. Many input and output methods throw exceptions and these exceptions need to be caught in a try catch format."


ex:

if you use a method for input that requires an int, and the user enters a double, it will fail, throwing an exception. Methods like that need to be in try/catch structures.