1. Limitations of exceptions
When overriding a method, only those exceptions listed in the exception description of the base class method can be thrown. This means that when the code used by the base class is applied to its derived class object, the same can be paid, and exceptions are no exception.
The following example is a limitation imposed on exceptions at compile time:
Public class baseballexception extends Exception {} Public class foul extends baseballexception{} Public class Strike extends baseballexception{} Public Abstract class inning { Public inning()throwsbaseballexception{} Public void Event()throwsbaseballexception{} Public Abstract void Addbat()throwsStrike,foul; Public void Walk() {}} Public class stormexception extends Exception{} Public class rainedout extends stormexception{} Public class Popfoul extends foul{} Public interface Storm { Public void Event()throwsRainedout; Public void Rainhard()throwsRainedout;} Public class strommyinnerings extends inning implements Storm{ /** * @throws baseballexception * * Public strommyinnerings()throwsRainedout,baseballexception {} Public strommyinnerings(String s)throwsrainedout,baseballexception{}/** * @throws rainedout * * @Override Public void Rainhard()throwsRainedout {}/** * @throws Strike * * @Override Public void Addbat()throwsPopfoul {} Public void Event(){} Public Static void Main(string[] args) {strommyinnerings strommyinnerings;Try{strommyinnerings =NewStrommyinnerings (); Strommyinnerings.addbat (); }Catch(Rainedout e) {System.out.println ("Rainedout"); }Catch(Popfoul e) {System.out.println ("Popfoul"); }Catch(Baseballexception e) {System.out.println ("Baseballexception"); } inning inning;Try{inning =NewStrommyinnerings (); Inning.addbat (); }Catch(Strike e) {System.out.println ("Strike"); }Catch(Foul e) {System.out.println ("Foul"); }Catch(Rainedout e) {System.out.println ("Rainedout"); }Catch(Baseballexception e) {System.out.println ("Baseballexception"); } }}
In the inning class, you can see that both the constructor and the event () method declare that an exception will be thrown, but it is not actually thrown. This allows you to force the user to catch an exception that might be added to the event () version after the overwrite, so it is reasonable. This is also true for abstract methods such as Addbat ().
Interface Storm is noteworthy because it contains a method defined in inning event () and a method Rainhard () that is not defined in inning. Both of these methods throw new Exception rainedout. The event () method in storm cannot change the exception interface of the event () method in inning if the Strommyinnerings class has a storm interface in the extended inning class. Otherwise, it is not possible to determine whether a normal exception was caught when using the base class. Of course, if the method defined in the interface does not come from a base class, such as Rainhard (), then there is no problem with what exception this method throws. The
exception limit has no effect on the constructor, and you will find that the Strommyinnerings constructor can throw any exception, regardless of the exception thrown by the base class constructor. The derived class constructor cannot catch exceptions thrown by the base class constructor.
Although the compiler enforces the exception description during inheritance, the exception description itself is not part of the method type, and the method type consists of the name of the method and the type of the parameter. Therefore, the method cannot be overloaded based on the exception description. Additionally, an exception that appears in the base class method does not necessarily appear in the exception description of the derived class method. In other words, in the process of inheritance and overwriting, the "interface of exception description" of a particular method is not larger but smaller-this is exactly the same as when the class interface is inherited.
2. Constructor
If a class inherits a class and implements an interface, they have the same interface method, but all throw different catch exceptions, when the subclass implements and overrides the method, no catch exceptions can be thrown at the method declaration. If the calling parent class constructor throws a catch exception, the corresponding constructor for the subclass can only be thrown and cannot be captured in the constructor. The correct cleanup method when the constructor throws an exception: for example, when a file is opened in the constructor, the cleanup action can be cleaned only after the object has been used and the user invokes a special cleanup method, rather than being closed directly to the finally block in the constructor. Because the finally block is closed regardless of whether an exception occurs, and the execution of the constructor succeeds, the file stream needs to be outside. However, if an exception is thrown when the file is opened successfully, you need to close the file and throw an exception message to the outside world:
Public classInputfile {PrivateBufferedReaderinch; Public Inputfile(String fname) throws exception{Try{inch=NewBufferedReader (NewFileReader (fname)); }Catch(FileNotFoundException e) {System. out. println ("Could not open"+fname);ThrowE }Catch(Exception e) {Try{inch. Close (); }Catch(IOException E1) {System. out. println ("In.close () unsuccessful");ThrowE }finally{ } } } PublicStringGetLine() {String s;Try{s=inch. ReadLine (); }Catch(IOException e) {Throw NewRuntimeException ("ReadLine () failed"); }returnS } Public void Dispose(){Try{inch. Close (); System. out. println ("Dispose () successful"); }Catch(IOException e) {Throw NewRuntimeException ("In.close () failed"); }} Public classCleanUp { Public Static void Main(string[] args) {Try{Inputfile Inputfile =NewInputfile ("D:/workspace/testjava/src/com/test/cleanup.java");Try{String s;inti =1; while((s = inputfile.getline ())! =NULL) { } }Catch(Exception e) {System. out. println ("Caught Exception in main"); E.printstacktrace (System. out); }finally{Inputfile.dispose (); } }Catch(Exception e) {System. out. println ("Inputfile construction failed"); } }}
The Inputfile constructor accepts a string as a parameter that represents the name of the file to open. In a try block, the FileReader object is created with this file name. The FileReader object itself is not very useful, but it can be used to build BufferedReader objects. Note that the advantage of using inputfile is to combine the two-step operation. This general cleansing idiom should also be used when the constructor does not throw any exceptions, with the basic rule of entering an try-finally statement block immediately after creating the object to be cleaned.
3. Exception matching
When an exception is thrown, the exception handling system finds the "most recent" handler in the order in which the code is written. After a matching handler is found, it considers the exception to be processed and then no longer finds it.
Lookups do not require an exact match to the exception declared by the thrown exception handler. The object of a derived class can also match the handler for its base class, as in the following example:
Public class annoyance extends Exception{} Public class sneeze extends annoyance{} Public class Human { Public Static void Main(string[] args) {Try{Throw NewSneeze (); }Catch(Sneeze e) {System.out.println ("Catch Sneeze"); }Catch(Annoyance e) {System.out.println ("Catch annoyance"); }Try{Throw NewSneeze (); }Catch(Annoyance e) {System.out.println ("Catch annoyance exception"); } }}
The sneeze exception is replaced by the first matching catch, which is the first one in the program. However, if you delete this catch, leaving only the catch clause of annoyance, the landscape will still work, as this replenishment is the base class for sneeze. In other words, catch (annoyance E) captures annoyance and all exceptions derived from it.
If you put the catch clause at the top of the capturing base class to "mask" the exception of the derived class, like this:
try { throw new Sneeze(); }catch (Annoyance e) { //... } catch (Sneeze e) { //..... }
This way the compiler will find that the sneeze catch clause is never executed and therefore will be an error.
4. Other options available
An important principle of exception handling is "Catch exceptions only if you know how to handle them." In fact, an important goal of exception handling is to separate the error-handling code from the place where the error occurred. This allows you to focus on what you want to accomplish in a piece of code, and how to handle the error in another piece of code. In this way, the skeleton code is not mixed with error-handling logic and is easier to understand and maintain.
"Checked exceptions" can complicate the problem because they force you to be forced to add the CACTH child name when it may not be ready to handle the error, even if we don't know how to handle it, which leads to the exception being hidden:
try{ //… throw …}catch(Exception e){//什么都不做}
Convert "checked exception" to "Unchecked exception": When calling other methods in a common method, consider "I don't know how to handle this exception, but I can't swallow it, or just print some useless messages". JDK1.4 's anomaly chain provides a new way to solve this problem by wrapping the "checked exception" into the RuntimeException:
try{ //… throw 检查异常…}catch(IDontKnowWhatToDoWithThisCheckedException e){ Thrownew RuntimeException(e);}
It's a good idea to "shield" the "checked anomaly" function. You do not have to "swallow" the exception, and you do not have to put it in the exception declaration of the method, and the exception chain can ensure that you do not lose any of the original exception information. You can also deal with it in "where you know how to handle it," or you can pass the throw E.getcause () in other upper catch. The original "checked exception" is thrown again.
5. Exception Usage Guide
The exception should be used in the following cases:
1) deal with the problem at the right level. (Catch an exception if you know what to do with it.) )
2) Resolve the problem and recall the method that generated the exception.
3) do a little patching and then go around the place where the exception was generated.
4) Calculate with other data to replace the value expected to be returned by the method.
5) Try to finish what you can do in the current operating environment and then re-throw the same exception to the higher level.
6) Try to finish what you can do in the current operating environment and throw the different exceptions to the higher level.
7) terminate the program.
8) to simplify.
9) Make class libraries and programs more secure.
6. Summary
Exceptions are an integral part of Java programming, and if you don't know how to use them, you can only do very limited work. One of the things about exception handling is that it allows you to focus on the problem you're dealing with somewhere, and on the other side, the errors that are generated in the code you write.
Java Programming thought reading notes 12th through exception handling errors (bottom)