Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Tutorial 34 (Handling Exceptions)
- //Exception is part of an error handling mechanism
- //---------------------------------------------------------------------------------------------------------------------------------------
- //demo1/App.java:
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- public class App {
- public static void main(String[] args) throws FileNotFoundException {
- File file = new File("test.txt");
- FileReader fr = new FileReader(file);
- }
- }
- /*when you run it you should get an error in red:
- Exception in thread "main" java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
- at java.io.FileInputStream.open(Native Method)
- at java.io.FileInputStream.<init>(Unknown Source)
- at java.io.FileReader.<init>(Unknown Source)
- at App.main(App.java:16)
- */
- //---------------------------------------------------------------------------------------------------------------------------------------
- //demo2/App.java:
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- public class App {
- public static void main(String[] args) {
- File file = new File("test.txt");
- try {
- FileReader fr = new FileReader(file);
- // This will not be executed if an exception is thrown.
- System.out.println("Continuing ....");
- } catch (FileNotFoundException e) {
- System.out.println("File not found: " + file.toString()); //Remember to Right click>new>file>text.txt or else you will get an error: File Not Found test.txt
- }
- System.out.println("Finished.");
- }
- }
- /*run results:
- Continuing ....
- Finished.
- */
- //---------------------------------------------------------------------------------------------------------------------------------------
- //demo3/App.java:
- package demo3;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- public class App {
- public static void main(String[] args) {
- try {
- openFile();
- } catch (FileNotFoundException e) {
- System.out.println("Could not open file"); //if error, user will see "Could not open file"
- }
- }
- public static void openFile() throws FileNotFoundException {
- File file = new File("test.txt");
- FileReader fr = new FileReader(file);
- }
- }
- /*
- run results should be blank if successful
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement