Try/Catch Block

Here’s the format for trying code that might cause problems, and then catching and handling the errors:

try 
{
    //code that might cause problems
}
catch (Exception e) 
{
    //handle the error
}

Suppose I try to read from a file that doesn’t exist. That could certainly cause problems! To handle this, I’m going to try reading from a file, and then catch any problems:

Scanner console = new Scanner(System.in);
try 
{
    System.out.print("Input the name of a file: ");
    String name = console.nextLine();
    Scanner fileIn = new Scanner(new File(name));
    String line = fileIn.nextLine();
    System.out.printf("1st line: %s%n", line);
}
catch (Exception e) 
{
    System.out.println("Error reading file.");
    System.exit(1); //exits the program
}

In this example, ask the user for the name of an input file. We try reading and printing the first line of that file. If something goes wrong, we catch the exception, print an error message, and exit the program.