When programming there is the normal flow of logic that solves your problem, and a second flow of logic that handled "Exceptional" unexpected situations. Java uses the type Exception
and the keyword throw
to have bits of code present exceptional error states.
Your program, when being complied, is being checked for its ability to handle exceptional return values. Since you didn't handle the exceptional return value, it is not going to be compiled.
Below is your code, handling this Exception
. Pay close attention to the try
and catch
block structure, as it is how one writes code that can handle an Exception
being raised. However, don't be constrained by how I handled the exception for you, because the details of how to handle the exception are dependent on what you would prefer to do.
import java.io.*;
import java.util.*;
public class story {
private static Scanner x;
public static void main(String[] args) {
String story = "";
try {
x = new Scanner(new File("names.txt"));
} catch (FileNotFoundException error) {
System.out.println("the program failed because \"names.txt\" was not found.");
return -1;
}
while(x.hasNext()){
story = story + x;
}
System.out.println(story);
}
}
There is another approach to handling exceptions that sometimes is appropriate, which is to "not handle" the exception. When doing so, change the method from whatever the method was
to whatever the method was throws Exception
. For example public static void main(String[] args)
to public static void main (String[] args) throws Exception
.
While this handles the compiler's complaint it should be used sparingly because exceptions that bubble up through the nested method calls past the main
method will crash the program, typically without easily readable output that might make the error easier for a human to fix.