The program is difficult to perfect, inevitably have a variety of anomalies. For example, the program itself has a bug, such as the program printing when the printer has no paper, such as insufficient memory. To resolve these exceptions, we need to know why the exception occurred. For some common anomalies, we can also provide a certain response plan. Exception handling in C is done simply by function return values, but the meaning of the return value is often determined by practice. Programmers need to query large amounts of data before they can find a reason for ambiguity. Object-oriented languages such as C + +, Java, Python tend to have more complex exception handling mechanisms. The exception handling mechanism in Java is discussed here.
Java Exception Handling
Exception Handling
A large part of Java's exception handling mechanism comes from C + +. It allows the programmer to skip a problem that is temporarily unavailable to continue the development, or to allow the program to make smarter processing based on the exception.
Java uses some special objects to represent the exception state, so that the object is called an exception object. When an exception occurs, Java throws (throw) The object that represents the current state, based on a predetermined setting. The so-called throw is a special way to return. The thread pauses, stepping out of the method call, until an exception handler (Exception Handler) is encountered. The exception handler can catch (catch) The exception object, and according to the object to determine the next action, such as:
- Remind users
- Handling Exceptions
- Continue the program
- Exit program
- ......
The exception handler looks like this, which consists of a try, catch, finally, and subsequent block of programs. Finally is not a must.
Try { ...;} catch() { ...;} catch() {...;} finally {...;}
This exception handler monitors the block behind the try. the parentheses of a catch have a parameter that represents the type of exception you want to catch. Catch captures the corresponding type and its derived class. The block following the try contains the action to be taken against the exception type. A try-monitored block may throw more than one type of exception, so an exception handler can have multiple catch modules. Finally, the program block is the program that executes regardless of whether an exception occurs.
In try, we put in a program that could be faulted, need to be monitored, and design an exception-handling scenario in the catch.
The following is a partial Java program that uses exception handling. The program in the Try section reads a line of text from a file. In the process of reading the file, there may be ioexception that occur:
BufferedReader br =New BufferedReader (New FileReader ("file.txt")); try {StringBuilder sb = new StringBuilder (); String line = br.readline (); while (line! = null) {sb.append (line); Sb.append ("\ n"); line = br.readline ();} String everything = sb.tostring ();} Catch(IOException e) {
E.printstacktrace (); System.out.println ("IO problem");} finally {br.close ();}
If we snap to the IOException class object E, we can manipulate the object. For example, call the object's Printstacktrace () to print the status of the current stack. In addition, we have printed the hint "IO problem" to the midrange.
Regardless of whether there is an exception, the program eventually enters the finally block. We close the file in the finally block, emptying the resource that the file descriptor occupies.
type of Exception
Exception classes in Java are inherited from the Throwable class. An object of the Throwable class can be thrown (throw).
Orange: unchecked; Blue: Checked
Throwable objects can be divided into two groups. One group is unchecked exceptions, and exception handling mechanisms are often not used for this set of exceptions, including:
- the error class usually refers to an internal error in Java and an error such as resource exhaustion. When error (and its derivative classes) occur, we cannot resolve the error at the programming level, so we should exit the program directly.
- The exception class has a special derivative class runtimeexception. RuntimeException (and its derived classes) are caused by the Java program itself, that is, because programmers make mistakes in programming . RuntimeException can be avoided entirely by correcting Java programs. For example, to convert an object of one type to another type that does not have an inheritance relationship, that is, classcastexception. Such exceptions should and can be avoided.
The rest is the checked exception. These classes are programmed to interact with the environment causing the program to fail at run time . For example, when reading a file, because the file itself is wrong, ioexception occurs. Another example is the Web server temporarily changes the URL point, causing malformedurlexception. File systems and Web servers are outside of the Java environment and are not controlled by programmers. If the programmer can anticipate exceptions, the exception handling mechanism can be used to prepare the response plan. For example, if the file is faulty, remind the system administrator. For example, when a problem occurs on the network server, remind the user and wait for the network server to recover. the exception handling mechanism is primarily used to handle such exceptions.
Throw Exception
In the above program, exceptions come from our call to the Java IO API. We can also throw exceptions in our own programs, such as the following battery class, with charging and using methods:
PublicClasstest{PublicStaticvoidMain (string[] args) {Battery abattery =NewBattery (); Abattery.chargebattery (0.5); Abattery.usebattery (-0.5); }}ClassBattery {/*** Increase battery*/Publicvoid Chargebattery (DoubleP) {//Power <= 1if (This.power + P < 1.) {This.power =This.power +P }Else{This.power = 1.; } }/*** Consume battery*/PublicBoolean Usebattery (DoubleP) {Try{test (P);}Catch(Exception e) {System.out.println ("Catch Exception"); System.out.println (E.getmessage ()); p = 0.0; }if (This.power >=P) {This.power =This.power-PReturnTrue; }Else{This.power = 0.0;ReturnFalse; } } /** * Test usage * /private void Test (double p) throws Exception //I just throw, do N ' t handle { if (P < 0) {Exception e = new Exception ("P must be positive"); throw e;}} private double power = 0.0; // percentage of battery}
Usebattery () indicates the use of battery operation. The Usebattery () method has a parameter that represents the amount of power used. We test the parameter using the test () method. If the parameter is negative, then we think there is an exception and throw.
In test, when an exception occurs (P < 0), we create a exception object E and use a string as the argument. The string contains information about the exception that is not required. throws the exception object with a throw.
We have an exception handler in Usebattery (). Because the test () method does not directly handle the exception it produces, it throws the exception to the Upper Usebattery (), so in the definition of test () we need to throws exception to illustrate.
(Assuming that the exception handler is not in Usebattery (), but in the higher-level main () method, we also add throws Exception in the definition of usebattery () . )
In catch, we use the GetMessage () method to extract the information contained in its exception. The operation results of the above program are as follows:
Catch Exception
P must be positive
In the exception handler, we will catch any exception class or its derived class exception. This often does not help us identify problems, especially when a program may throw multiple exceptions. We can provide a more specific class to capture.
Custom Exceptions
We can create new exception classes through inheritance. When inheriting, we often need to rewrite the constructor method. An exception has two constructor methods, one without parameters and one with a string parameter. Like what:
Extends exception{public public Super(msg);}}
We can provide more exception-related methods and information in the derived classes.
When customizing exceptions, carefully select the inherited base class. A more specific class should contain more exception information, such as IOException relative to exception.
Summary
Exception handling is a problem that is being solved and is also in the manufacturing. In large projects, excessive, fine-grained exception handling often causes the program to become a mess. The design of exception handling is not simple and requires careful use.
Java Advanced 02 Exception handling