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 with throw into a catch clause is basically the same as passing a parameter 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. Reference 6

1. Why Use exceptions

For C programs, use error code to do so, why introduce exceptions? Because exceptions cannot be ignored. If a function represents an exception state by setting a state variable or returning an error code, there is no way to guarantee that the function caller will necessarily detect the variable or test the error code. The resulting program will continue to run from the abnormal state it encounters, the exception is not captured, and the program terminates 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 to complete and exception handling acquaintances, but MSDN describes the use of longjmp in C + +   To adjust the stack, it is not possible to call destructors on local objects, 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, and can not ignore this notification, ② and searching the stack in order to find the exception code, ③ also ensure that the local object destructor is called. and C + + exception handling is just to solve these problems. </p> <p> There are places where exceptions can be used to solve problems, such as the types of errors that cannot be caught or determined in the current context, and 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 essential 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, no matter how the function exits. (Only one exception is when you call longjmp.) This drawback of longjmp is the main reason C + + is the first to support exception handling)

despite C + + specification for first introduction of exceptions

despite C + + the specification of the exception was introduced for the first time, 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 with throw into a catch clause is basically the same as passing a parameter through a function call.

There are some similarities, but there are huge differences. </p> <p> Let's start with the same point. The way you pass a function argument to an exception can be a pass-through, a reference, or a pass pointer, which is the same. But when you pass parameters and exceptions, the process of doing this is completely different. The reason for this difference is that when you invoke a function, the control of the program is eventually 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 operating system developers use S E H to make the system stronger.    We can also use S E H to 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 b a C K) function that the operating system can call 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 and reference by the operating system. <br> adding S E H support in the compiler is not an easy task. It's not surprising that different compiler vendors will implement S E H in different ways. Fortunately, we don't have to consider the implementation details of the compiler, only 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, the other is checked Exception. Java requires that a function be written to the declaration part of a function for a checked Exception that is not handled by a catch.

. NET only runtimeexception

in addition to error and runtimeexception, the rest of the exception is what you need to care about, and these exception classes collectively referred to as checked Exception, as for the 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 automatically ...

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

6.exception Business Process Control can learn from it)

when usingUseCaseto describe a scene, there is a stream 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, andCatchthere is an anomaly flow inside, hereExceptiondoes not represent an exception or an error in the program,Exceptionis just an object-oriented approach to business logic control. If I don't understand that, then I don't think I really understand how to use it.Javato the correct programming.  
and I wrote the program myself and would customize a lot ofExceptionclass,all of these Exception classes do not imply that the program has an exception or an error, but represents the occurrence of a non-primary event stream ., which is used to control the flow of those branching processes. For example, if you add a user to a permission system, you should define1an exception class,userexistedexception, throwing this exception does not mean that you have failed to insert the action, only that you have encountered a branching process, left behind theCatchto handle this branching process. Traditional programmers will write aif Elseto deal with, and a qualifiedOOPprogrammers should be aware of the use ofTry Catchway to differentiate between the main event stream andNthe processing of a branching process, throughTry Catch, but notif Elseto 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 for methods in earlier versions.

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

You can add a declaration that throws a exceptionb in the Foo method of the base class, however, this destroys the open-close principle. Also, sometimes we have no way to modify the parent class, such as when overloading a class in a JDK.

Another possible approach is to catch exceptionb in the Extend Foo method, and then construct a exceptiona and throw it. It's a viable option, but it's just a stopgap measure.

9. Checked Exception convert re

To avoid writing the throws part in a function declaration, you can often 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 "The Design and Evolution of C + +", Bjarne Stroustrup also mentioned, also based on the consideration of this issue, C + + has no "Static Checking" (checked exceptions) instead, use "Run time Checking". And Stroustrup suggests that for a new exception d to be thrown, it can be inherited from an existing exception so that no existing code is affected, and the new code can handle it. (This is the conclusion that Stroustrup made in 90!) )

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

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

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

· In addition to runtimeexception, other inherited from java.lang.Exception exception is collectively referred to as Checked Exception, How many kinds do they have ?

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. Reference

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

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.