Results 1 to 6 of 6
Thread: Try/catch block
- 07-02-2009, 07:52 AM #1
Member
- Join Date
- Mar 2009
- Posts
- 42
- Rep Power
- 0
Try/catch block
public class UseTry
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String getName()
{
try
{
return br.readLine();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
It gives an error "Method must return a result of type string" ..There is a solution if i explicitly throw Exception Like this
String getName() throws IOException
{
return br.readLine();
}
No error here..but the problem is that my program requires i should not explicitly throw the exception...
Can u all suggest sumthing to rectify this problem..
Thanks :)
- 07-02-2009, 07:58 AM #2
Senior Member
- Join Date
- Dec 2008
- Location
- Hong Kong
- Posts
- 473
- Rep Power
- 5
you may declare and initialize varialbe xxx
and xxx = br.realine()
return xxx at the end of method
OR
return xxx in finally block
- 07-02-2009, 09:54 AM #3
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
The error is you've not return anything from the complete path. Say in try block anything is not return due to any reason. So outside of the try-catch block you've not return anything too. But your method expecting to return something, and failed. Those things are validate in compile time.
Java Code:String getName() { try { return br.readLine(); } catch (IOException e){ e.printStackTrace(); } return ""; }
- 07-02-2009, 09:58 AM #4
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
- 07-02-2009, 11:24 AM #5
Member
- Join Date
- Mar 2009
- Posts
- 42
- Rep Power
- 0
Reply...
:) Thanks ...
- 07-02-2009, 02:32 PM #6
- Join Date
- Jul 2007
- Location
- Colombo, Sri Lanka
- Posts
- 11,374
- Blog Entries
- 1
- Rep Power
- 18
:) If you solve the problem please mark it as solved as well. It's really helpful to all other members, looking into your thread.
Similar Threads
-
Try- catch block + return + IO package
By vasavi.singh in forum New To JavaReplies: 1Last Post: 02-23-2009, 10:09 AM -
Question reg try/catch block
By nn12 in forum New To JavaReplies: 1Last Post: 09-16-2008, 05:56 PM -
System.exit() in catch block.
By new_2_java in forum Advanced JavaReplies: 8Last Post: 06-24-2008, 03:45 PM -
Try Catch block issues
By kewlgeye in forum New To JavaReplies: 11Last Post: 04-29-2008, 07:10 AM -
try...catch block
By javaplus in forum New To JavaReplies: 3Last Post: 11-06-2007, 07:53 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks