1. Attempt to "fix" exception
In the previous examples, we just caught the exception, but didn't try to fix it.
Let's take an example:
public class SalesReport { public static void main(String[] args) { String filename = "SalesData.txt"; // File name int months = 0; // Month counter double oneMonth; // One month's sales double totalSales = 0.0; // Total sales double averageSales; // Average sales try { // Open the file. File file = new File(filename); Scanner inputFile = new Scanner(file); // Process the contents of the file. while (inputFile.hasNext()) { // Get a month's sales amount. oneMonth = inputFile.nextDouble(); // Accumulate the amount. totalSales += oneMonth; // Increment the month counter months++; } // Close the file. inputFile.close(); // Calculate the average. averageSales = totalSales / months; // Display the results. JOptionPane.showMessageDialog(null, String.format("Number of months: %d\n" + "Total Sales: $%,.2f\n" + "Average Sales: $%,.2f", months, totalSales, averageSales)); } catch(FileNotFoundException e) { // Thrown by the Scanner constructor when // the file is not found. JOptionPane.showMessageDialog(null, "The file " + filename + " does not exist."); } catch(InputMismatchException e) { // Thrown by the Scanner class's nextDouble // method when a non-numeric value is found. JOptionPane.showMessageDialog(null, "Non-numeric data found in the file."); } System.exit(0); } }
This program reads the monthly sales from the file and returns the total. The program may encounter two problems, FileNotFoundException and inputmismatch exception. When these two exceptions occur, the program will not exit directly, but will print two error messages, but the program can't continue to execute next (what is continued execution? For example, after encountering inputmismatch exception, skip this row of data and continue to read the data of the next row). How to avoid being affected by exceptions?
import java.io.*; // For File class and FileNotFoundException import java.util.*; // For Scanner and InputMismatchException import javax.swing.JOptionPane; // For the JOptionPane class /** This program demonstrates how exception handlers can be used to recover from errors. */ public class SalesReport2 { public static void main(String[] args) { String filename = "SalesData.txt"; // File name int months = 0; // Month counter double oneMonth; // One month's sales double totalSales = 0.0; // Total sales double averageSales; // Average sales // Attempt to open the file by calling the // openfile method. Scanner inputFile = openFile(filename); // If the openFile method returned null, then // the file was not found. Get a new file name. while (inputFile == null) { filename = JOptionPane.showInputDialog( "ERROR: " + filename + " does not exist.\n" + "Enter another file name: "); inputFile = openFile(filename); } // Process the contents of the file. while (inputFile.hasNext()) { try { // Get a month's sales amount. oneMonth = inputFile.nextDouble(); / Accumulate the amount. totalSales += oneMonth; // Increment the month counter. months++; } catch(InputMismatchException e) { // Display an error message. JOptionPane.showMessageDialog(null, "Non-numeric data found in the file.\n" + "The invalid record will be skipped."); // Skip past the invalid data. inputFile.nextLine(); } } // Close the file. inputFile.close(); // Calculate the average. averageSales = totalSales / months; // Display the results. JOptionPane.showMessageDialog(null, String.format("Number of months: %d\n" + "Total Sales: $%,.2f\n" + "Average Sales: $%,.2f", months, totalSales, averageSales)); System.exit(0); } /** The opeFile method opens the specified file and returns a reference to a Scanner object. @param filename The name of the file to open. @return A Scanner reference, if the file exists Otherwise, null is returned. */ public static Scanner openFile(String filename) { Scanner scan; // Attempt to open the file. try { File file = new File(filename); scan = new Scanner(file); } catch(FileNotFoundException e) { scan = null; } return scan; } }
Suppose the file read by the program is:
24987.62
26978.97
abc
31978.47
22781.76
29871.44
Operation results:
After the change, the program can skip the exception and continue to run even if it encounters an exception. In fact, the idea is very simple, that is, write the try catch statement into the loop. After an exception occurs somewhere, enter the catch statement and change the operation object in the catch statement (in this example, change the Scanner's scanning object to the next line) , then jump out of the try catch, enter the loop outside the try catch, and then enter the try catch statement. At this time, due to the change of objects in the try, the try statement may not report errors, so as to achieve the purpose of skipping exceptions.
2. finally statement
After the try catch statement, you can choose to add a finally statement. The basic format is as follows:
try { (try block statements . . . ) } catch (ExceptionType ParameterName) { (catch block statements . . . ) } finally { (finally block statements . . . ) }
If the program throws an exception, the finally statement will be executed after the catch statement. If no exception is thrown, the finally statement will be executed after the try statement. In short, the finally statement will be executed whether the program throws an exception or not.
3. When an exception is not caught
Exceptions must be handled by the written or default exception handler. When an exception is thrown in a method, the normal execution of the method will stop, and the JVM will search the method for a matching exception handler. If there is no handle to handle the exception in this method, the previous method in the heap (that is, the method calling the method with the exception) will be found Whether the exception can be handled. If the exception still cannot be handled, the call stack is passed to the previous method again. This situation continues until the main method. If the main method does not handle the exception, the program will stop and the default exception handler will handle the exception.
/** This program demonstrates the stack trace that is produced when an exception is thrown. */ public class StackTrace { public static void main(String[] args) { System.out.println("Calling myMethod..."); myMethod(); System.out.println("Method main is done."); } /** MyMethod */ public static void myMethod() { System.out.println("Calling produceError..."); produceError(); System.out.println("myMethod is done."); } /** produceError */ public static void produceError() { String str = "abc"; // The following statement will cause an error. System.out.println(str.charAt(3)); System.out.println("produceError is done."); } }
4,throwsÂ
When a method may throw an exception and the exception should be handled (what exceptions don't need to be handled? For example, exceptions inherited from the error class, which you can't handle through code. Or exceptions like array subscript out of bounds can sometimes not be handled, because such exceptions should be avoided directly when writing programs. Exceptions like fileNotFound should be handled) , we should match the corresponding handle for this method; or require the method to throw an exception and be handled by the method calling this method (if the upper layer method still has no handle, continue to throw it until we find the method that can be handled). Examples are as follows:
public void displayFile(String name) throws FileNotFoundException
Throws means that the exception generated in this method is handed over to the called place for processing. After calling the method declared by throws, no matter whether there is an exception in the operation, you must use the try...catch statement for exception processing. After the main method uses throws, the exception will be handed over to the JVM for processing, and then the program call will be ended.