What Is an Abnormal End?
Exception handling, known in English as exceptional handling, is a new method that replaces the declining error code method, and provides specific advantages that error code cannot. Exception handling separates receiving and handling error codes. This function clears the programmer's mind, and also helps the code to be more readable, and easier for the maintainer to read and understand. Exception handling (also known as error handling) features provide a way to handle any unexpected or abnormal situations that occur while the program is running. Exception handling uses the try, catch, and finally keywords to try potentially unsuccessful operations, handle failures, and clean up resources after the fact.
- Chinese name
- Exception handling
- Foreign name
- exceptional handling
- Substitute
- Declining error code method
- Also known as
- Error handling
- Field
- computer
- Function
- Provides methods for handling abnormal situations
- Keywords
- try, catch, and finally keywords
- Exception handling, known in English as exceptional handling, is a new method that replaces the declining error code method, and provides specific advantages that error code cannot. Exception handling separates receiving and handling error codes. This function clears the programmer's mind, and also helps the code to be more readable, and easier for the maintainer to read and understand. Exception handling (also known as error handling) features provide a way to handle any unexpected or abnormal situations that occur while the program is running. Exception handling uses the try, catch, and finally keywords to try potentially unsuccessful operations, handle failures, and clean up resources after the fact.
- Exception handling is a mechanism in a programming language or computer hardware that is used to handle abnormal conditions that occur in software or information systems (that is, certain special conditions that exceed the normal execution flow of a program).
Overview of exception handling
- Exception handling is a mechanism in a programming language or computer hardware that is used to handle abnormal conditions that occur in software or information systems (that is, certain special conditions that exceed the normal execution flow of a program).
- Various programming languages have very significant differences in handling exceptions (the difference between error detection and exception handling is that error detection is in the normal program flow, code that deals with unforeseen problems, such as a call operation that does not end successfully). Some programming languages have functions that cannot be safely called when input has illegal data, or that the return value cannot be effectively distinguished from an exception. For example, the atoi function in C language (ASCII string to integer conversion) can return 0 when the input is illegal. In this case, the programmer needs to perform additional error detection (possibly through some auxiliary global variables such as C's errno), or perform input checking (such as through regular expressions), or use both methods together.
- Through exception handling, we can control and prompt users for illegal input in the program to prevent the program from crashing.
- From a process perspective, hardware interrupts are equivalent to recoverable exceptions, although interrupts are generally not related to the program flow itself.
- From the subprogrammer's perspective, exceptions are a useful mechanism for notifying the outside world that the subprogram cannot execute normally. If the data entered is invalid (for example, the divisor is 0), or the required resources are not available (for example, the file is missing). If the system does not have an exception mechanism, the programmer needs to use the return value to indicate which errors occurred.
Exception handling programming language exception mechanism
- Many common programming languages, including Actionscript, Ada, BlitzMax, C ++, C #, D, ECMAScript, Eiffel, Java, ML, Object Pascal (such as Delphi, Free Pascal, etc.), Objective-C, Ocaml, PHP (version 5) , PL / 1, Prolog, Python, REALbasic, Ruby, Visual Prolog, and most .NET programming languages. The built-in exception mechanism searches backwards along the function call of the function call stack until it encounters the exception handling code. Stack unwinding is generally done step by step during the search of this exception handling code. The exception is Common Lisp, which does not take a stack rollback, thus allowing execution to resume in place at the point where the exception was thrown after the exception has been handled. Visual Basic (especially in versions earlier than .net, such as 6.0) goes further: the on error statement can easily specify whether to resume (resume) or skip (resume next) or execute the programmer after an exception occurs. Defined error handler (goto ***).
- The syntax of the exception mechanism in most languages is similar: throw or raise an exception object (Java or C ++, etc.) or a special extensible enumerated value (such as Ada language); the scope of the exception handling code is Marker clause (language scope starting with try or begin) marks its start, and its end is marked by the first exception handling clause (catch, except, resuce, etc.); several exception handling clauses can appear in succession Handle specific types of exceptions. Some languages allow an else clause for situations where no exceptions occur. More common is the finally, ensure clause, which will be executed regardless of whether an exception occurs, used to release some resources required for exception handling.
- C ++ exception handling is the basis of Resource-Acquisition-Is-Initialization.
- C is generally considered to not support exception handling. The Perl language can optionally support structured exception handling.
- Python is very general and in-depth about exception handling, so it is very difficult to write programs without try, except.
Explanation of Exception Handling Terms
- Exception handling, known in English as exceptional handling, is a new method that replaces the declining error code method, and provides specific advantages that error code cannot. Exception handling separates receiving and handling error codes. This function clears the programmer's mind, and also helps the code to be more readable, and easier for the maintainer to read and understand.
- Exception handling (also known as error handling) features provide a way to handle any unexpected or abnormal situations that occur while the program is running. Exception handling uses the try, catch, and finally keywords to try potentially unsuccessful operations, handle failures, and clean up resources after the fact.
- Exception handling is usually the action taken to prevent unknown errors. The advantage of exception handling is that you no longer have to rack your brains to think about various errors, which provides a very effective method for handling a certain type of error, which greatly improves the programming efficiency.
- Exceptions can be generated by the common language runtime (CLR), third-party libraries, or application code using the throw keyword.
Exception Handling Features
- 1. An exception occurs when an application encounters an abnormal condition, such as a division by zero condition or an out-of-memory warning.
- 2. When an exception occurs, control flow immediately jumps to the associated exception handler (if one exists).
- 3. If there is no exception handler for the given exception, the program will stop executing and an error message will be displayed.
- 4. Operations that may cause exceptions are performed with the try keyword.
- 5. Exception handlers are blocks of code that are executed when an exception occurs. In C #, the catch keyword is used to define an exception handler.
- 6. Programs can throw exceptions explicitly using the throw keyword.
- 7. The exception object contains detailed information about the error, including the status of the call stack and a textual description of the error.
- 8. Even if an exception is thrown, the code in the finally block executes, allowing the program to release resources.
Basic model of exception handling
- One is called the "termination model" (it is a model supported by Java and C ++). In this model, it is assumed that errors are so critical that the program cannot return to the place where the exception occurred. Once the exception is thrown, It means that the error can't be undone, and it can't come back to continue execution.
- The other is called the "recovery model." It means that the job of the exception handler is to fix the error, and then retry the method of calling the problem, and think that it will succeed the second time.
- For the recovery model, it is usually hoped that the program can continue to execute after the exception is handled. In this case, throwing the exception is more like a call to a method-you can configure this method in Java to get recovery-like behavior (That is, instead of throwing an exception, but calling the method to correct the error.) Or, put the try block in a while loop so that you can continue to enter the try block until you get a satisfactory result.
- Although the recovery model started to look very attractive, and the operating system people used also supported exception handling of the recovery model, programmers eventually turned to using code similar to the "termination model". Because: the handler must pay attention to the exception thrown Location, which necessarily contains non-generic code that depends on where it is thrown. This increases the difficulty of writing and maintaining the code, especially for large programs where exceptions may be thrown from many places.
- Below I write a simple example passed under VC ++ 6.0
- #include <iostream>
- using namespace std;
- class Error
- public:
- virtual void show () = 0;
- class DenoError: public Error
- public:
- void show ()
- cout << "The denominator cannot be 0!" << endl;
- void main ()
- int a, b;
- cin >> a >> b;
- try
- DenoError e;
- if (b == 0)
- throw e;
- int c = a / b;
- cout << c << endl;
- catch (DenoError & e)
- e.show ();
Exception handling method
php Exception handling php exception
- Extending PHP's built-in exception handling classes
- [1] Users can extend the built-in exception handling classes of php with custom exception handling classes. The following code illustrates which properties and methods are accessible and inheritable in subclasses in the built-in exception handling class. Translator's Note: The following code is just to illustrate the structure of the built-in exception handling class, it is not a practically useful code.
- Built-in exception handling classes
- <? php class Exception {protected $ message = 'Unknown exception'; // exception information protected $ code = 0; // user-defined exception code protected $ file; // file name where the exception occurred protected $ line; // occurred Line number of the exception function __construct $ message = null $ code = 0); final function getMessage (); // return exception information final function getCode (); // return exception code final function getFile (); // return exception File name final function getLine (); // returns the line number of the code where the exception occurred final function getTrace (); // backtrace () array final function getTraceAsString (); // getTrace () information transformed into a string / * Overloadable methods * / function __toString (); // output string}?> If you use a custom class to extend the built-in exception handling class, and you want to redefine the constructor, it is recommended to call parent :: __construct () to check if all variables have been assigned. When an object wants to output a string, you can override __toString () and customize the output style.
- Extending PHP's built-in exception handling classes
- <? php / ** * Customize an exception handling class * / class MyException extends Exception {// redefine the constructor to make message a property that must be specified public function __construct ($ message $ code = 0) {, // Custom code // Ensure that all variables are assigned the correct parent :: __construct ($ message $ code);} // Custom string output style * / public function __toString () {return __CLASS__. ": [{$ this-> code}]: {$ this-> message} / n ";} public function customFunction () {echo" A Custom function for this type of exception / n ";}} / ** * Create one for testing Class of exception handling mechanism * / class TestException {public $ var; const THROW_NONE = 0; const THROW_CUSTOM = 1; const THROW_DEFAULT = 2; function __construct ($ avalue = self :: THROW_NONE) {switch ($ avalue) {case self: : THROW_CUSTOM: // throw a custom exception throw new MyException ('1 is an invalid parameter' 5); break; case self :: THROW_DEFAULT: // throw the default exception throw new Exception ('2 isnt allowed as a parameter ' 6); break; default: // Create an object without exception $ this var = $ avalue; break;}}}
Java Java Exception Handling
- [2] Do you think you are a Java expert? Beijing Haidian Oracle Learning Center has helped you to fully grasp Java's exception handling mechanism. In the following code, can you quickly find the six problems of exception handling?
OutputStreamWriter out = ... java.sql.Connection conn = ... try {// Statement stat = conn.createStatement (); ResultSet rs = stat.executeQuery ("select uid, name from user"); while (rs.next ()) { out.println ("ID:" + rs.getString ("uid") // + ", Name:" + rs.getString ("name")); } conn.close (); // out.close (); } catch (Exception ex) // { ex.printStackTrace (); // , }
- As a Java programmer, you should be able to identify at least two issues. However, if you can't figure out all six questions, keep reading this article.
- This article does not discuss the general principles of Java exception handling, as these principles are already well known to most people. What we have to do is to analyze various common bad habits that can be called "anti-patterns" that violate good coding standards, to help readers become familiar with these typical negative examples, so that they can be acutely aware of and avoid these in actual work. problem.
- Counter example 1: discard exception
- Code: 12-15 lines.
- This code catches the exception without doing anything, and can be regarded as a killer in Java programming. Judging by the frequency and scourge of the problem, it may be comparable to a notorious problem in C / C ++ programs-it does not check whether the buffer is full. If you see this kind of discard (not throw) exception, you can be 99% sure that there is a problem with the code. Comments to avoid misunderstanding).
- The error of this code is that an exception (almost) always means that something is wrong, or at least something unusual has happened, and we should not remain silent and indifferent to the distress signal sent by the program. Calling printStackTrace is not "handling exceptions". Yes, calling printStackTrace is helpful for debugging programs, but after the debugging phase of the program ends, printStackTrace should no longer bear the main responsibility in the exception handling module.
- It is very common to drop exceptions. Opening the documentation of the JDK's ThreadDeath class, you can see the following paragraph: "Specifically, although the occurrence of ThreadDeath is a 'normal situation', the ThreadDeath class is a subclass of Error rather than Exception, because many applications will capture all Exception and then discard it and ignore it. "This sentence means that although ThreadDeath represents a common problem, because many applications will try to catch all exceptions and not handle them properly, JDK defines ThreadDeath as Subclass Error, because Error class represents a serious problem that ordinary applications should not catch. It can be seen that the bad habit of discarding exceptions is so common that it has even affected the design of Java itself.
- So, how to correct it? There are four main options:
- 1. Handle exceptions. Take some action on the anomaly, such as correcting the problem, reminding someone, or doing some other processing, and determine the action that should be taken based on the specific situation. Once again, calling printStackTrace is not a "handled exception."
- 2. Rethrow the exception. After analyzing the exception, the code that handles the exception thinks that it cannot handle it, and it is an option to re-throw the exception.
- 3. Convert the exception into another exception. In most cases, this means converting a low-level exception into an application-level exception (an exception whose meaning is more easily understood by the user).
- 4. Don't catch exceptions.
- Conclusion 1: Now that you have caught the exception, you need to handle it appropriately. Do not catch the exception and discard it afterwards.
- Counterexample 2: Do not specify a specific exception
- Code: 12 lines.
- Many times people are attracted to the "wonderful" idea: catch all exceptions with a catch statement. The most common case is the use of a catch (Exception ex) statement. But in practice, in most cases, this approach is not worth promoting. why?
- To understand why, we must review the purpose of the catch statement. The catch statement indicates that we expect an exception to occur and we want to be able to handle it. The purpose of the exception class is to tell the Java compiler what kind of exception we want to handle. Since most exceptions are derived directly or indirectly from java.lang.Exception, catch (Exception ex) is equivalent to saying that we want to handle almost all exceptions.
- Take a look at the previous code example. What exceptions do we really want to catch? The most obvious one is SQLException, which is a common exception in JDBC operations. Another possible exception is IOException, because it operates on OutputStreamWriter. Obviously, it is not appropriate to handle these two very different exceptions in the same catch block. It would be much better to catch SQLException and IOException separately with two catch blocks. That is to say, the catch statement should try to specify the specific exception type, and should not specify the Exception class that is too broad.
- On the other hand, in addition to these two specific exceptions, there are many other exceptions that may also occur. For example, what if executeQuery returns null for some reason? The answer is to let them continue to throw, that is, you don't have to capture or process them. In fact, we can't and shouldn't catch all the exceptions that may occur, and there are opportunities to catch exceptions elsewhere in the program-until the end is handled by the JVM.
- Conclusion two: Specify specific exception types in the catch statement as much as possible, and use multiple catches if necessary. Don't try to handle all possible exceptions.
- Counter-example three: Occupied resources are not released
- Code: 3-11 lines.
- The exception changed the normal execution flow of the program. Although this principle is simple, it is often overlooked. If the program uses resources such as files, sockets, and JDBC connections, even if it encounters an exception, it must properly release the occupied resources. To this end, Java provides a keyword that simplifies such operations.
- Finally is such a good thing: Finaly guarantees that the code that performs the cleanup task will always have a chance to execute before the end of the try / catch / finally block, whether or not there is an exception. Unfortunately, some people are not used to using finally.
- Of course, you should be careful when writing finally blocks, especially pay attention to the exceptions thrown within the finally block-this is the last chance to perform the cleaning task, and try not to have difficult errors.
- Conclusion three: ensure that all resources are properly released. Make full use of finally keywords.
- Counterexample 4: Does not explain the details of the exception
- Code: 3-11 lines.
- Take a closer look at this code: What happens if an exception occurs inside the loop? Can we get enough information to determine the cause of the error inside the loop? No. We can only know that some error has occurred in the class currently being processed, but we cannot obtain any information to determine the cause of the current error.
- The stack trace function of printStackTrace shows the execution flow of the program running to the current class, but only provides some basic information, fails to explain the actual cause of the error, and is not easy to interpret.
- Therefore, when an exception occurs, it is best to provide some text information, such as the currently executing classes, methods, and other status information, including organizing and organizing the information provided by printStackTrace in a more suitable way.
- Conclusion 4: Provide a proper amount of error cause information in the exception handling module, and organize the error information to make it easier to understand and read.
- Counterexample 5: Too large try block
- Code: 3-11 lines.
- It is often seen that someone puts a lot of code into a single try block, which is actually not a good practice. The reason why this phenomenon is common is that some people save their time and don't want to spend time analyzing which lines of code in a large block of code will throw exceptions, and what are the specific types of exceptions. Putting a large number of sentences into a single huge try block is like stuffing all the daily necessities into a large box when traveling. Although the things are brought, it is not easy to find them.
- Some novices often put a lot of code into a single try block, and then declare Exception in the catch statement, instead of separating each possible paragraph and catching the exception separately. This approach makes it difficult to analyze the reason why the program throws an exception, because there are too many places in a large piece of code that may throw Exception.
- Conclusion 5: Minimize the volume of the try block.
- Counterexample 6: Incomplete output data
- Code: 7-8 lines.
- Incomplete data is the stealth killer of Java programs. Take a closer look at this code and consider what would happen if an exception was thrown in the middle of the loop. The execution of the loop is of course interrupted. Secondly, the catch block will be executed ?? That's all, there is no other action. What about the data that has already been output? The person or device using the data will receive an incomplete (and therefore incorrect) data, but will not receive any hint as to whether the data is complete. For some systems, incomplete data may cause greater losses than when the system is down.
- The ideal solution is to write some information to the output device to declare the incompleteness of the data; another possible effective method is to buffer the data to be output first, prepare all the data, and then output it all at once.
- Conclusion 6: Consider all possible exceptions and their impact on the execution process.
- Rewritten code
- Based on the discussion above, the rewritten code is given below. Some people may say that it is a little bit stingy, but it has a more complete exception handling mechanism.
OutputStreamWriter out = ... java.sql.Connection conn = ... try { Statement stat = conn.createStatement (); ResultSet rs = stat.executeQuery ("select uid, name from user"); while (rs.next ()) { out.println ("ID:" + rs.getString ("uid") + ", name:" + rs.getString ("name")); } } catch (SQLException sqlex) { out.println ("Warning: Incomplete data"); throw new ApplicationException ("SQL error while reading data", sqlex); } catch (IOException ioex) { hrow new ApplicationException ("IO error while writing data", ioex); } finally { if (conn! = null) { try {conn.close (); } catch (SQLException sqlex2) { System.err (this.getClass (). GetName () + ".mymethod-Cannot close database connection:" + sqlex2.toString ());} } if (out! = null) { try { out.close (); } catch (IOException ioex2) { System.err (this.getClass (). GetName () + ".mymethod-Cannot close output file" + ioex2.toString ()); } } }