3 Replies - 168 Views - Last Post: 04 November 2012 - 05:04 AM Rate Topic: -----

#1 BrendanH  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 174
  • Joined: 05-May 12

Exceptions

Posted 04 November 2012 - 04:43 AM


import java.io.*;
public class Exception {
  public static void main(String []args) {
    try {
      RandomAccessFile raf =
        new RandomAccessFile("myfile.txt", "r");
      byte b[] = new byte[1000];
      raf.readFully(b, 0, 1000);
    }
    catch(FileNotFoundException e) {
      System.err.println("File not found");
      System.err.println(e.getMessage());
      e.printStackTrace();
     }
    catch(IOException e) {
      System.err.println("IO Error");
      System.err.println(e.toString());
      e.printStackTrace();

     }
   }
 }


The book says FileNotFoundException is a subclass of IOException but how? as FileNotFoundException is above IOException
Like · · Unfollow post · 8 minutes ago

This post has been edited by BrendanH: 04 November 2012 - 04:44 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Exceptions

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6051
  • View blog
  • Posts: 23,483
  • Joined: 23-August 08

Re: Exceptions

Posted 04 November 2012 - 04:50 AM

The fact the FileNotFound is a subclass of IOException is not related to its position in this code; it's defined as such in the Java class libraries.

You want to catch more specific exceptions before the general (superclass) exception. If IOException preceded FileNotFoundException here, you would only ever get the general (superclass) IOException instead of the more specific FileNotFoundException because it was found first. Reason for doing this is that FileNotFound is generally a recoverable error you want to return to the user so they can provide a file that exists.
Was This Post Helpful? 1
  • +
  • -

#3 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Exceptions

Posted 04 November 2012 - 04:51 AM

The order of the catch clauses does not indicate any relationships. The API pages will show genealogy.
Was This Post Helpful? 1
  • +
  • -

#4 BrendanH  Icon User is offline

  • D.I.C Head

Reputation: -2
  • View blog
  • Posts: 174
  • Joined: 05-May 12

Re: Exceptions

Posted 04 November 2012 - 05:04 AM

Thanks Jack that makes sense! :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1