Dark Horse programmer--java Learning Note Five (exception)

Source: Internet
Author: User
Tags stack trace throw exception try catch

1, exception: is an abnormal condition that occurs during runtime. in Java, the object is described and encapsulated in the form of a class. A class that describes an unhealthy condition is called an exception class.  in combination with normal process code and problem-handling code, the normal process code and problem-handling code are now separated to improve readability. In fact, the exception is Java through the object-oriented thinking of the problem encapsulated into an object, with the exception class to describe it. different problems are described in different classes. such as the corner of the bounds, null pointer exception, and so on. a lot of problems, meaning that the description of the class is also a lot, the generality of the extraction, forming an anomaly system.  the abnormal situation is divided into two main categories:Throwable: Whether it's an error, an exception, a problem, the problem should be thrown, let the caller know and handle it. //The system is characterized by the fact that Throwable and all its subclasses have a parabolic nature. What does it mean to be parabolic? How can we embody the parabolic nature? in fact, through two key words to reflect. throws throw, all classes and objects that can be manipulated by these two keywords have a parabolic nature.  |--1, generally not handled: Errorfeature: The severity issue that is thrown by the JVM. This problem occurs, generally not targeted treatment, directly modify the program. |--2, can be handled by: Exception the characteristics of the system:the suffix of the subclass is suffixed with its parent name, and is highly readable.  1, compile-time is detected exception: As long as the exception and its subclasses are, in addition to the special sub-class RuntimeException system. Once this problem occurs, it is hoped that it will be detected at compile time, so that the problem can be handled in a corresponding way. Such problems can be dealt with in a targeted way.  2, no exception is detected at compile time (runtime exception): Is the runtimeexception in exception and its subclasses. This problem occurs, cannot allow the function to continue, the operation can not run, more because of the cause of the call or caused the internal state changes caused. then this problem is generally not handled, directly compiled through, at run time, let the caller call the program force stop, let the caller adjust the code. So when customizing exceptions, either inherit exception or inherit runtimeexception.   2, the error and all exceptions of the RuntimeException class are called unchecked exceptions, all others are called checked exceptions, and the compiler checks to see if an exception handler is provided for all of the checked exceptions. The problem needs to be dealt with:1, user input error. 2, device error. 3, physical limitations. 4, code error.  exceptions derived from RuntimeException are contained in several cases:the type conversion of the error. array access is out of bounds. accesses a null pointer. exceptions that are not derived from RuntimeException include:an attempt was made to read data after the end of the file. an attempt was made to open a file that does not exist. an attempt was made to look up a class object based on a given string, and the string represented by it does not exist.   The following four scenarios require an exception to be thrown:1, call a method that throws a checked exception. 2, the program finds an error while running and throws a checked exception with the throw statement. 3, the program has an error, for example, a[-1]= 0 throws an unchecked exception such as Arrayindexoutexception. An internal error occurred 4,java the virtual machine and the runtime library. The first two cases must tell the programmer who called this method to throw an exception.  3, the catch form of exception handling:The way in which exceptions can be handled in a targeted manner.  the specific format is:try{//code that requires an exception to be detected. }catch (Exception class variable)//This variable is used to receive the exception object that occurred{//The code that handles the exception. }finally{//code that is bound to execute;}Note:there is only one case where the finally code block will not be executed, that is, System.exit (0) was executed previously.
 processing Process:An exception detected in try passes the exception object to the Catch,catch to catch the exception for processing. Finally, it is often used to close resources. For example: Database resources, IO resources and so on. It is important to note that the try is a separate block of code in which the variable defined is valid only in that variable block. If you continue to use outside of a try, you need to establish a reference outside the try and initialize it in try. Io,socket will meet you.  4, the principle of exception handling:1, function content if you throw an exception that needs to be detected, then the function must be declared. Otherwise, it must be captured within the function with Try/catch, or the compilation will fail.  2, if the function that declares the exception is called, then Try/catch, or throws, or the compilation fails.  3, when catch, when throws? The function content can be solved, with catch. can not solve, with throws to tell the caller, by the caller resolved.  4, a function if more than one exception is thrown, then the call must have a corresponding multiple catch for targeted processing. inside there are several exceptions that need to be detected, just throw a few exceptions, throw a few, and catch a few. multiple catch clauses can be merged in JAVA7. when you re-throw a new exception in the catch clause, you should use Newexceptions.init (oldexception). Then call New.getcause () to get the original exception. if a checked exception occurs in a method and is not allowed to be thrown, the wrapper technique is useful to wrap it into a runtime exception class. If you want to record only one exception, then re-throw it:try{Access the database} catch (Exception e) {Logger.log (level, message, e);throw e;}However, before java7, it is problematic to assume that it is used in the public void UpdateRecord () throws SQLException. The compiler will indicate that the method can throw any excep and not just sqlexception. Now that the problem has improved, the compiler will track e from the try block, assuming that the only checked exception in this try block is a SqlException instance, and that it is not changed in the catch block, declaring the perimeter method as throws sqlexceptions is legal.  5, try Catch finally code block combination features:1,try Catch Finally2,try catch (multiple) when no resource needs to be freed, you can not define the finally. the 3,try finally exception cannot be directly catch processing, but the resource must be closed.  Example:void Show () throws exception{try{//Open Resourcesthrow new Exception ();}finally{//Close Resources     }}An unexpected result occurs when a return statement is included in the finlly clause. If you exit from a try statement block with a return statement, the contents of the finlly clause are executed before the method returns. If there is also a return statement in Finlly, the return value will overwrite the original return value.  It is strongly recommended that you use try catch and try finally statement blocks independently, which can improve the clarity of your code. For exampleInputStream in = ....try {try {code that might throw exception    }finally {in.close ();    }}catch (IOException e) {Show error message}try block with resource, try{Work with the resource} finlly {Close the resource}if the resource belongs to a class that implements the Autocloseble interface, Res.close () is called automatically when the try block exits.  6, exception Note:1,runtimeexception and its subclasses can be thrown out of a function without being declared on the function. 2, when a subclass overrides a parent class method, the method of the parent class throws an exception, and the child class's method can only throw the exception of the parent class or the subclass of the exception. 3, if the parent throws more than one exception, the child class can only throw a subset of the parent class exception. Simply put: Subclasses overriding a parent class can only throw exceptions to a parent class or a subset of subclasses.  Note:if the method of the parent class does not throw an exception, then the subclass can never be thrown when it is overwritten, only try.  7, stack trace is a list of method invocation procedures, and the Stacktraceelement class has detailed information.  8, the assertion mechanism allows some check statements to be inserted into the surrogate during testing, which will be automatically removed when the code is released. form: Assert: Condition or assert condition: expressionBoth forms detect the condition and, if the result is false, throws a Assertinerror exception, in the second form, the expression is passed into the Assertionerror constructor and converted to a message string. Enable assertion: Java-enableasserting (-disableasserting) or-ea (-da), in a package, then:-ea:package
9, Package: Packeage, not known as the nameless package.
classify and manage class files. provides a multilevel namespace for a class. write in the first line of the program file. The name of the class is the package name. Class name. packages are also a form of encapsulation.  The classes in the package are accessed , the classes in the package being accessed must be public, and the methods of the classes in the package being accessed must also be public.  Access between Packages
The class permissions in the package being accessed must be public.
Member permissions in the class: public or protected
Protected is a permission that is provided for subclasses in other packages
The Nameless package and the class with the package name, without the package, are the nameless packages.
There is only one public class in a class, and the source file must be the same as the class name, if there is no public, the source file name is arbitrary.
When you import the same class name,
The use of a nameless package must be in the same directory.
Com.solaire.enhance.Week has the package name is the main, then is and com.solaire.enhance.*, is the non-package name mainly. Same as
If you have a package name, add the full name path.
Import
simplifies the class name.
There is only one package in a program file, but you can have more than one import.
JAVA5 can provide static import.
jar Package:Java's compressed package. easy to carry the item. easy to use, just set the jar path in Classpath. the database driver, SSH framework, etc. are all embodied in jar package.  operation of the jar packageThe operation of the jar through the Jar.exe tool. Create a jar packagejar-cvf mypack.jar packa packbView jar PackagesJAR-TVF Mypack.jar [> directed file]UnzipJAR-XVF Mypack.jarCustom jar Package manifest filejar–cvfm mypack.jar mf.txt packa packb

 

Dark Horse programmer--java Learning Note Five (exception)

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.