Atitit. The use of exceptions summarizes best practices for Java. NET PHP vo8f

Source: Internet
Author: User
Tags try catch

Summary of the use of Atitit.java anomalies best practices vo8f

1. Why use exception 1

2. throwing an exception into a catch clause with a throw is basically the same as passing a number of parameters through a function call. 2

3. main motives of S E H 2

4. RuntimeException and checked Exception 2

5. Do you want to use checked Exception 3

6. Exception Business Process Control can be used for reference ) 3

7. Disadvantages of checked Exception 4

8. The Base class and extension class throws special exceptions that are not the same way of solving 4

9. Checked Exception convert re 4

10. Throw a new Exception d, which allows it to inherit from an existing exception. 4

11. List the five types of runtimeexception most commonly used : 5

12. The following are the exception classes listed in the JDK API: except for RuntimeException, checked Exception 5

13. References 6

1. Why Use exceptions

For C programs, you can use error code. Why do you introduce exceptions? Because exceptions cannot be ignored.

Suppose a function represents an exception state by setting a state variable or by returning an error code. There is no way to ensure that the function caller will be certain to check the variable or test error code. The resulting program proceeds from the exception state it encounters, and the exception is not caught. The program will terminate execution immediately.

In the C program. We can use int setjmp (Jmp_buf env), and void longjmp (jmp_buf env, int value), these 2 functions are finished and exception handling is known, but MSDN describes using longjmp in C + + to adjust STA You cannot call a destructor on a local object when CK. But for C + + programs.   Destructors are important (I usually put the object's delete in the destructor). <br> so we need a method: ① can notify the exception state. You cannot ignore this notification, ② and searching the stack in order to find the exception code. ③ also make sure that the destructor for the local object is called. and C + + exception handling is just to solve these problems. </p> <p> Some places only practical talents to solve this problem. For example, in the current context. Unable to catch or determine the type of error, we have to throw an exception into the larger context. Also, the use of exception handling allows the error handler to be separated from the "usual" code, making the code more concise and flexible.

In addition, the program is indispensable to the robustness of the exception handling often plays an important role in it. </p>

Because the local object is always disposed when the function returns. Regardless of how the function exits. (Only one exception is when you call longjmp.)

This drawback of longjmp is the main reason for C + + leading support for exception handling)

Although C + + specification for first introduction of exceptions

Although C + + the specification for the first introduction of exceptions, but Java is mandatory " Check for exceptions " ( Checked Exception ) Specification of the only mainstream language

Author :: old Wow's paw attilax Ayron, email:[email protected]

Reprint please indicate source: Http://blog.csdn.net/attilax

2. Throwing an exception into a catch clause with a throw is basically the same as passing a number of parameters through a function call.

There are some of the same points, but there are huge differences. </p> <p> Let's start with the same point. The way you pass function parameters and exceptions can be to pass values, pass references, or pass pointers. That's the same.

But when you pass the number and the exception, the process of the system is completely different. The reason for this difference is that when you call a function, the control of the program is finally returned to the function's call, but when you throw an exception, control never returns to the place where the exception was thrown. </p>

3. Main motives of S E H

Microsoft's main motivation for introducing S E h in wi n d o W S is to facilitate the development of the operating system itself. The developer of the operating system uses S E H to make the system stronger.

We can also use S E H. Make our own programs stronger.

<br> the burden caused by the use of S E h is primarily borne by the compiler, not by the operating system.

<br> when the exception block (Exception block) appears, the compiler generates special code.    The compiler must produce some tables (t a b l e) to support the processing of the data structure of S E H. The <br> compiler must also provide a callback (c a l l b a C K) function. The operating system can invoke these functions to ensure that the exception block is processed.

The <br> compiler is also responsible for preparing the stack structure and other internal information for use by the operating system and references. <br> adding S E H support in the compiler is not an easy thing to do. Different compiler vendors will implement S E H in different ways. This is no surprise. Fortunately, we were able to do without having to consider the implementation details of the compiler, only using the S-E h function of the compiled program.

(In fact, most compiler vendors use Microsoft's recommended syntax)

4. RuntimeException and checked Exception

Java exception is divided into two categories, one is runtimeexception and its subclasses. Another category is checked Exception. Java requires that a function be written in the declaration portion of a function for checked Exception that are not handled by a catch.

. NET has only runtimeexception

except for error and runtimeexception. The rest of the exception is what you need to care about, and these exceptions are collectively referred to as checked Exception, as for error and RuntimeException is collectively referred to as unchecked Exception.

5. Do you want to use checked Exception

To use .... The advantage is the process Clr,and IDE ability to generate structure code on their own initiative ...

It is recommended to use the checked exception when encountering recoverable errors, and to use the unchecked exception when encountering an unrecoverable exception.

6.exception Business Process Control can learn from it)

when usingUseCaseto describe a scene, there is a flow of main events andNan exception stream. The exception flow can occur in the process of the main event flow, andTryThe main event stream is implemented in the statement, andCatchthe exception flow is implemented inside. In hereExceptiondoes not represent an exception or an error in the program,Exceptionis just an object oriented approach to business logic control. Assuming this is not clear, then I don't feel really sure how to useJavato the correct programming.  
and I wrote the program myself. Will define a large number of their ownExceptionclass,all of these Exception classes do not mean that the program has an exception or an error, just represents the occurrence of a non-primary event stream , which is used to control the flow of those branching processes. For example, you add a user to the permissions system. Should define1an exception class,userexistedexception. Throwing this exception does not mean that you have failed to insert the action, merely stating that you have encountered a branching process, left behindCatchto handle this branching process.

The traditional program ape will write an if else to handle. and a qualified OOP program Ape should consciously use the Try Catch method to differentiate between the main event stream and the n -branch process, by Try Catch , but not if Else to isolate the different event streams from the code for separate code writing .

7. Disadvantages of checked Exception

Support for unchecked exceptions:
The checked exception that propagates upward along the call stack destroys the top-level method, because these methods must declare exceptions thrown by all of the methods they call.

Check exceptions are thrown as part of the method interface, which makes it difficult to add or remove exceptions to methods in the previous version number.

8. The base class and extension class throws special exceptions that are not the same way of solving

The ability to add a declaration that throws a exceptionb in the Foo method of the base class, however, destroys the open-close principle. And, sometimes we have no way to change the parent class, for example, when overloading a class in a JDK.

Another possibility is to catch exceptionb in the Extend Foo method, and then construct a exceptiona and throw it.

This is a workable approach, but it is only a stopgap measure.

9. Checked Exception convert re

To avoid writing the throws part in a function declaration, it is often possible to see the following code in a Java project to ' Swallow ' Exception:

10. Throw a new Exception d, which allows it to inherit from an existing exception,

[III] in "The Design and Evolution of C + +", Bjarne Stroustrup also mentions that the same is also based on consideration of this issue, C + + has no "Static Checking" (checked exceptions) instead of using "Run time Checking". Also Stroustrup suggests. For dropping a new exception, D, allows it to inherit from an existing exception, which does not affect the existing code. The new code can also handle it. (This is the conclusion that Stroustrup made in 90!)

11. List the five types of runtimeexception most commonly used:

This is the most common topic in the Java Certification exam, in fact, runtime exception the most common, often encountered, also on 5, 6 kinds, such as the following:

ArithmeticException

int a=0;
int b= 3/a;

ClassCastException:

Object x = new Integer (0);
System.out.println ((String) x);

Indexoutofboundsexception
ArrayIndexOutOfBoundsException,
Stringindexoutofboundsexception

int [] numbers = {1, 2, 3};
int sum = numbers[3];

IllegalArgumentException
NumberFormatException

int a = Interger.parseint ("test");

Nullpointerexceptionextends

· Except runtimeexception. Other inherited from the java.lang.Exception Anomaly collectively referred to as Checked Exception, How many of them ?

12. The following are the exception classes listed in the JDK API:
Except RuntimeException, it's checked Exception.

Java.lang.Object
Java.lang.Throwable
Java.lang.Exception
All implemented interfaces:
Serializable
Directly known subclasses:
aclnotfoundexception, activationexception, alreadyboundexception, applicationexception,  awtexception, backingstoreexception, badattributevalueexpexception,  badbinaryopvalueexpexception, badlocationexception, badstringoperationexception,  brokenbarrierexception, certificateexception, classnotfoundexception,  clonenotsupportedexception, dataformatexception, datatypeconfigurationexception,  destroyfailedexception, executionexception, expandvetoexception, fontformatexception,  Generalsecurityexception, gssexception, illegalaccessexception, illegalclassformatexception,  InstantiationException, InterruptedException, IntrospectionException,  invalidapplicationexception, invalidmididataexception, invalidpreferencesformatexception,  invalidtargetobjecttypeexception, invocationtargetexception, ioexception, jaxbexception,  Jmexception,&nBsp keyselectorexception, lastownerexception, lineunavailableexception, marshalexception,  Midiunavailableexception, mimetypeparseexception, mimetypeparseexception, namingexception,  NoninvertibleTransformException, NoSuchFieldException, NoSuchMethodException,  notboundexception, notownerexception, parseexception, parserconfigurationexception,  printerexception, printexception, privilegedactionexception, propertyvetoexception,  refreshfailedexception, remarshalexception, runtimeexception, saxexception,  Scriptexception, servernotactiveexception, soapexception, sqlexception, timeoutexception,  TooManyListenersException, TransformerException, TransformException,  unmodifiableclassexception, unsupportedaudiofileexception, unsupportedcallbackexception,  Unsupportedflavorexception, unsupportedlookandfeelexception, urireferenceexception, urisyntaxexception, userexception, xaexception, xmlparseexception,  Xmlsignatureexception, xmlstreamexception, xpathexception

13. References

Anders Hejlsberg on why not introduce Java -like checked exceptions in C# - Products and Technologies - Sadie Web . htm

C + + handles exception tricks . htm

[ reprint ]java of the checked Exceptions and unchecked Exception _4527_ Sina Blog . htm

Atitit. The use of exceptions summarizes best practices for Java. NET PHP vo8f

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.