java - Can't get the try-catch-finally block to work -
i have struggled long time try-catch-finally block work. i'm beginner in java, , learning how read/write/handle exceptions. in task i'm trying read 2 separate .txt files. 1 has countries , population, other has countries , area of country. further printed out new file information countries , area per person displayed.
i'm not sure if can put inside try-catch block. i'm getting error message "unhandled filenotfoundexception etc.". i've been trying for long time now, , can't work properly.
private string country; private double value; scanner in1 = new scanner(new file("countrypopulation.txt")); scanner in2 = new scanner(new file("countryarea.txt")); printwriter out = new printwriter("countryareaperinhabitant"); public ioandexceptionhandling(string line) { int = 0; while (!character.isdigit(line.charat(i))) { i++; } this.country = line.substring(0, - 1).trim(); this.value = double.parsedouble(line.substring(i).trim()); } public string getcountry() { return this.country; } public double getvalue() { return this.value; } public void printareaperperson() { try { try { while (in1.hasnextline() && in2.hasnextline()) { ioandexceptionhandling country1 = new ioandexceptionhandling(in1.nextline()); ioandexceptionhandling country2 = new ioandexceptionhandling(in1.nextline()); double density = 0; if (country1.getcountry() == country2.getcountry()) { density = country2.getvalue() / country1.getvalue(); out.println(country1.getcountry() + " : " + density); } } } { in1.close(); in2.close(); out.close(); } } catch (filenotfoundexception f) { system.out.println("filenotfound!"); } catch (ioexception e) { e.printstacktrace(); } } thanks! :)
the block goes after catch blocks. execute regardless of exception being thrown or successful completion of block.
scanner in1; //field declaration no assignment scanner in2; //field declaration no assignmetn /* omitted class declaration & other code */ try { in1 = new scanner(new file("countrypopulation.txt")); //these require fnf caught in2 = new scanner(new file("countryarea.txt")); while (in1.hasnextline() && in2.hasnextline()) { ioandexceptionhandling country1 = new ioandexceptionhandling( in1.nextline()); ioandexceptionhandling country2 = new ioandexceptionhandling( in1.nextline()); double density = 0; if (country1.getcountry() == country2.getcountry()) { density = country2.getvalue() / country1.getvalue(); out.println(country1.getcountry() + " : " + density); } } } catch (filenotfoundexception f) { system.out.println("filenotfound!"); } catch (ioexception e) { e.printstacktrace(); } { in1.close(); in2.close(); out.close(); } the first rendition of code throwing unhandled exception error because inner try block did not catch filenotfoundexception. though had try...catch wrapping try block, did catch filenotfoundexception, exception not propogate upwards through nested try..catch statements
Comments
Post a Comment