Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need help in understanding exceptions

Status
Not open for further replies.

786snow

Programmer
Nov 12, 2006
75
Hi, I am trying to understand how exception work. I understand the code below.


Code:
  try {
        BufferedReader in = new BufferedReader(new FileReader("infilename.txt"));
        String str;
        while ((str = in.readLine()) != null) {
            //process(str);
             System.out.print("it did not works");

        }
        in.close();
    } 
    
    catch (FileNotFoundException ex) {
       System.out.print("file not found");
    }
}
    
    catch (IOException e) {  System.out.print("file can not be opened");
        e.printStackTrace();
    }

 
}

But I do not understand in the following code they decalaed "throws IOException' in the method declaration with out any catch and try, how does that work?


Code:
public void readFile(Sring filename) throws IOException {


while (numBytes <= myBuffer.length){  myInputStream.read(myBuffer);
nymByres;++
}
 
When you use that method you are required to enclose the call in a try/catch statement. This means the calling function will deal with any errors that occur, rather than the called function.

Code:
[blue]
YourObject obj = new YourObject();

try
{
  obj.readFile("test.txt");
}
catch (IOException e)
{
  [green]//You are dealing with the error which occured in the read File method where you called it in the code, rather than inside the readfile method.[/green]
  System.out.println("Something happened!\n"+e.toString());
}

[/blue]

But, please be sure to read the link posted by Diancecht.


Hope that helps,
Ron


typedef map<GiantX,gold, less<std::shortestpathtogold> > AwesomeMap;
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top