Results 1 to 4 of 4
Thread: try...catch block
- 11-05-2007, 09:26 PM #1
Member
- Join Date
- Nov 2007
- Posts
- 97
- Rep Power
- 0
try...catch block
Hi,
I am trying to explore try catch block. I know a bit about it, but I am confused a little. How can I use multiple catch blocks with a try. And whats the use of finally in try catch block?
I normally use try catch in following way:
Java Code:try{ ... } catch(Exception ex) { ex.printStackTrace(); }
Regards.Last edited by javaplus; 11-06-2007 at 08:18 PM.
- 11-05-2007, 10:26 PM #2
The more specific you can be the more information you can get about the trouble and thus the better equipped you can be to recover from it. Exceptions can be caught from more specific to more general. Using finally is a way to cleanup if an exception causes you to leave the execution of your code, eg, an error in reading a file causes execution to leave your try block and ends up in a catch block skipping over the br.close() statement. You could close the reader in a finally block. In pseudocode:
Java Code:try { URL url = new URL(some_path); File file = new File(url.toURI()); BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file))); // read and process file br.close(); } catch(MalformedURLException mue) { System.out.println("Bad URL: " + mue.getMessage()); } catch(FileNotFoundException fnfe) { System.out.println("FileNotFound: " + fnfe.getMessage()); } catch(IOException ioe) { System.out.println("Read error: " + ioe.getMessage()); }
- 11-06-2007, 08:22 PM #3
Member
- Join Date
- Nov 2007
- Posts
- 97
- Rep Power
- 0
Thanks. So the example you gave, can have br.close() in finally block.
Java Code:try { URL url = new URL(some_path); File file = new File(url.toURI()); BufferedReader br = new BufferedReader( new InputStreamReader( new FileInputStream(file))); // read and process file } catch(MalformedURLException mue) { System.out.println("Bad URL: " + mue.getMessage()); } catch(FileNotFoundException fnfe) { System.out.println("FileNotFound: " + fnfe.getMessage()); } catch(IOException ioe) { System.out.println("Read error: " + ioe.getMessage()); } finally{ br.close(); }
- 11-06-2007, 08:53 PM #4
Similar Threads
-
need block letters??
By dc2acgsr99 in forum New To JavaReplies: 16Last Post: 01-29-2008, 09:31 AM -
try catch!?
By Joe2003 in forum Advanced JavaReplies: 2Last Post: 01-28-2008, 08:51 PM -
Try Catch
By Renegade85 in forum New To JavaReplies: 4Last Post: 12-03-2007, 05:10 PM -
when to use try...catch
By javaplus in forum New To JavaReplies: 2Last Post: 11-18-2007, 09:52 PM -
Use try and catch
By zoe in forum New To JavaReplies: 2Last Post: 07-25-2007, 08:50 PM
Bookmarks