This shows you the differences between two versions of the page.
Both sides previous revision Previous revision Next revision | Previous revision Next revision Both sides next revision | ||
java:exceptions_intro [2015/03/03 06:19] gthanos [Finaly Block] |
java:exceptions_intro [2015/03/03 06:36] gthanos [Exception Handler] |
||
---|---|---|---|
Line 106: | Line 106: | ||
Όπως βλέπουμε έχουμε το προηγούμενο παράδειγμα, εμπλουτισμένο όμως με κώδικα διαχείρισης της διαίρεσης με το μηδέν. Ο κώδικας θα αναγνωρίσει ότι υπάρχει δημιουργείται ''ArithmeticException'' και συγκεκριμένα διαίρεση με το μηδέν (0) και θα εκτυπώσει τα σχετικά μηνύματα. | Όπως βλέπουμε έχουμε το προηγούμενο παράδειγμα, εμπλουτισμένο όμως με κώδικα διαχείρισης της διαίρεσης με το μηδέν. Ο κώδικας θα αναγνωρίσει ότι υπάρχει δημιουργείται ''ArithmeticException'' και συγκεκριμένα διαίρεση με το μηδέν (0) και θα εκτυπώσει τα σχετικά μηνύματα. | ||
+ | |||
+ | === Ανοίγοντας ένα αρχείο για διάβασμα === | ||
Παρακάτω δίνεται ένα πιο σύνθετο παράδειγμα μία μεθόδου που διαβάζει ένα αρχείο κειμένου και το επιστρέφει στη μορφή ενός String. | Παρακάτω δίνεται ένα πιο σύνθετο παράδειγμα μία μεθόδου που διαβάζει ένα αρχείο κειμένου και το επιστρέφει στη μορφή ενός String. | ||
Line 116: | Line 118: | ||
| | ||
public String readFile(String path) { | public String readFile(String path) { | ||
- | | + | |
try { | try { | ||
File file = new File (path); | File file = new File (path); | ||
Line 123: | Line 125: | ||
String inputLine; | String inputLine; | ||
StringBuffer strDocument = new StringBuffer(); | StringBuffer strDocument = new StringBuffer(); | ||
- | try { | + | while ((inputLine = in.readLine()) != null) { |
- | while ((inputLine = in.readLine()) != null) { | + | strDocument.append(inputLine); |
- | strDocument.append(inputLine); | + | |
- | } | + | |
- | fReader.close(); | + | |
- | }catch(IOException ex) { | + | |
- | System.out.println("IOException occured while opening file or reading from file "+path); | + | |
- | System.out.println("Exiting..."); | + | |
- | System.exit(1); | + | |
} | } | ||
+ | fReader.close(); | ||
return strDocument.toString(); | return strDocument.toString(); | ||
} | } | ||
Line 138: | Line 134: | ||
System.out.println("The specified file was not found at "+ path); | System.out.println("The specified file was not found at "+ path); | ||
return ""; | return ""; | ||
+ | } | ||
+ | catch(IOException ex) { | ||
+ | System.out.println("IOException occured while opening file or reading from file "+path); | ||
+ | System.out.println("Exiting..."); | ||
+ | System.exit(1); | ||
} | } | ||
+ | return ""; | ||
} | } | ||
| | ||
Line 151: | Line 153: | ||
} | } | ||
- | } | + | }</code> |
- | </code> | + | |
==== Finaly Block ==== | ==== Finaly Block ==== |