An in-depth study and analysis of Java anomalies

Source: Internet
Author: User
Tags finally block getmessage throwable

For the content of this article, belong to the basic knowledge research category, do not think that after reading this article will be able to master the abnormal knowledge home. Remember: Do thousands of songs and then Xiao Sound, view thousands of swords and then the device, so I think there is not a lot of source reading experience, you can hardly know when to customize the exception, when you need to throw an exception.

Overview of Exception mechanisms

The exception mechanism is what the program does when an error occurs. Specifically, the exception mechanism provides a secure channel for program exits. When an error occurs, the process of executing the program changes, and the control of the program is transferred to the exception handler.

Process of exception handling

When an exception is thrown in the program, the program jumps out of the code that caused the exception in the program, the Java Virtual machine detects the catch block that handles the exception that matches the Try keyword, and, if found, the code in the catch block, then proceeds to execute the program. The code for the exception that occurred in the try block is not re-executed. If no catch block is found to handle the exception, the current thread that encounters the exception is aborted after all the finally block code is executed and the Uncaughtexception method of the Threadgroup that belongs to the current thread is called.

Structure of the exception

Exception inheritance structure: Throwable for base class, error and exception inheritance Throwable,runtimeexception and IOException inheritance exception. Error and RuntimeException and their subclasses become unchecked exceptions (unchecked), and other exceptions become checked exceptions (checked).

Error exception

The error indicates that the program has had a very serious, unrecoverable error while running, in which case the application can only abort, such as an error in the Java Virtual machine. Error is a unchecked Exception, and the compiler does not check that the error is handled and does not catch exceptions of type error in the program. In general, you should not throw exceptions of type error in your program.

RuntimeException exception

Exception exceptions include runtimeexception exceptions and other non-runtimeexception exceptions. RuntimeException is a unchecked Exception, which means that the compiler Movement rehabilitation Center does not check whether the program handles RuntimeException, and does not have to capture the runtimexception type of exception in the program. You do not have to throw the RuntimeException class in the method body declaration. When runtimeexception occurs, there is a programming error in the program, so you should find the wrong modification program instead of capturing RuntimeException.

Checked Exception anomalies

Checked Exception exception, which is also the most used in programming Exception, all inherited from Exception and not runtimeexception the exception is Checked Exception, In the IOException and ClassNotFoundException. The JAVA language stipulates that checked Exception must be processed, that the compiler checks for this, either declares the throw checked Exception in the method body, or captures checked Exception with a catch statement, Otherwise it cannot be compiled.

Throw an exception when declaring a method

Syntax: throws (slightly)

Why do I throw an exception in declaring a method?

Method throws an exception as important as the type of the method return value. If the method throws an exception without declaring that the method throws an exception, then the client programmer
You can call this method without writing the code that handles the exception. Then, in the event of an exception, there is no suitable exception controller to resolve the exception.

Why is the exception thrown must have been checked for exceptions? RuntimeException and error can be generated in any code, they do not need to be shown by the programmer to throw, and in the event of an error, the corresponding exception will be automatically thrown. When encountering error, programmers are generally powerless; when encountering runtimeexception, there must be a logic error in the program, to modify the program; only checked exceptions are the programmer's concern, and the program should and should only throw or handle checked exceptions. Just checking for exceptions is thrown by programmers, in two cases: the client programmer calls the library function that throws the exception, and the client programmer throws the exception using the throw statement himself.

Note: A subclass method that overrides a method of a parent class cannot throw more exceptions than the parent class method, so sometimes the method of the parent class is designed to declare an exception, but the code of the actual implementation method does not throw an exception, and the purpose is to make it easier for the subclass method to overwrite the parent class method when the exception can be thrown.

How to throw an exception in a method

Syntax: throw (slightly) throw what exception?

For an exception object, the really useful information is the object type of the exception, and the exception object itself is meaningless. For example, if the type of an exception object is ClassCastException, then the class name is the only useful information. So, when choosing what exception to throw, the key is to choose the class name of the exception that clearly describes the exception.

Exception objects usually have two constructors: one is a parameterless constructor, and the other is a constructor with a string that acts as an additional description of the exception object in addition to the type name.

Why do you create your own exceptions?

You need to create your own exception when the Java built-in exception does not explicitly describe the exception. It is important to note that the only useful information is the type name, so do not expend effort on the design of the exception class.

The difference between throw and throws
/** * Java Learning Exchange QQ Group: 589809992 we learn java! together. */PublicClasstestthrow{PublicStaticvoidMain (string[] args) {try {Calling a method with the throws declaration must explicitly catch the exceptionOtherwise, the throw throwchecked must be declared again in the Main method (-3); }catch (Exception e) {System.out.println (E.getmessage ());}Calling the method that throws the runtime exception can either explicitly catch the exception,You can also ignore the exception throwruntime (3); }PublicStaticvoidThrowchecked (int a)throws Exception {if (A > 0) { Span class= "hljs-comment" >//self-throwing exception exception //the code must be in a try block, or in a method with throws declaration throw new Exception ( "A has a value greater than 0, does not meet the requirements");}} public static void throwruntime (int a) {if (A > Span class= "Hljs-number" >0) {//self-throwing runtimeexception exception, you can explicitly catch the exception //can also completely disregard the exception, the exception is given to the method caller to handle throw new runtimeexception ( "A has a value greater than 0, does not meet the requirements");}}}     

Add: Another way to throwchecked a function is as follows:

public static void throwChecked(int a) { if (a > 0) { //自行抛出Exception异常 //该代码必须处于try块里,或处于带throws声明的方法中 try { throw new Exception("a的值大于0,不符合要求"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }

Note: The throwchecked in the main function does not have to be a try exception at this point.

Should you declare a method to throw an exception or catch an exception in a method?

Processing principle: Catching and dealing with exceptions that know how to handle, and passing those that do not know how to handle them

Releasing resources using the finally block

The finally keyword guarantees that the statements in finally will be executed regardless of whether the program leaves the try block in any way. The finally block is entered in the following three scenarios:

(1) The code in the try block is properly executed.

(2) throws an exception in the try block.

(3) Execute return, break, continue in the try block.

Therefore, when you need a place to execute code that must be executed under any circumstances, you can put the code in the finally block. When you use external resources in your program, such as database connections, files, and so on, you must write the code that frees these resources to the finally block.

It is important to note that an exception cannot be thrown in a finally block. The Java exception handling mechanism guarantees that, in any case, the finally block must be executed before leaving the try block, so when an exception occurs in the try block, the Java Virtual machine first goes to the finally block to execute the code in the finally block, and after the finally block executes, Throws an exception out again. If an exception is thrown in a finally block, the exception that is caught by the try block cannot be thrown, the exception that is caught externally is the exception information in the finally block, and the real exception stack information that occurs in the try block is lost. Take a look at the following code:

Connection  null;try{    con = dataSource.getConnection();    ……}catch(SQLException e){    ……    throw e;//进行一些处理后再将数据库异常抛出给调用者处理}finally{ try { con.close(); } catch(SQLException e){ e.printStackTrace(); ……}}

After running the program, the caller gets the following information

Java.lang.NullPointerException

At MyPackage.MyClass.method1 (methodl.java:266)

Instead of the database exception that we expect to get. This is because the con in this case is a null relationship, and NullPointerException is thrown in the finally statement, which can be avoided by increasing the judgment of whether Con is null in the finally block.

Missing exception

Take a look at the following code:

public void method2(){try{    ……    method1();  //method1进行了数据库操作}catch(SQLException e){ …… throw new MyException("发生了数据库异常:"+e.getMessage);}}public void method3(){ try{ method2();}catch(MyException e){ e.printStackTrace(); ……}}

In the METHOD2 code above, the try block captures the method1 thrown by the database exception SqlException, and throws a new custom exception myexception. There's nothing wrong with this code, but look at the console output:

MyException:发生了数据库异常:对象名称‘MyTable‘ 无效。 at MyClass.method2(MyClass.java:232) at MyClass.method3(MyClass.java:255)

The original exception SqlException information is lost, here can only see method2 inside the myexception stack of the definition, and the method1 of the database exception occurred in the stack is not seen, how to debug it, Only a row in the method1 line of code looks for the database operation statement.

The JDK developers are aware of this, and in JDK1.4.1, the Throwable class has added two constructor methods, public throwable (Throwable cause) and public throwable (String message , Throwable Cause), the original exception stack information passed in the constructor will be printed in the Printstacktrace method. But for programmers who are still using JDK1.3, they can only implement the ability to print the original exception stack information on their own. The implementation process is also simple, simply add a primitive exception field to the custom exception class, pass in the original exception in the constructor, and then overload the Printstacktrace method, first calling the Printstacktrace method of the original exception saved in the class, You can then call the Super.printstacktrace method to print out the original exception information. You can define the MyException class that appears in the preceding code:

Import Java.io.PrintStream;Import Java.io.PrintWriter;PublicClassMyExceptionExtendsexception{PrivateStaticFinalLong Serialversionuid =1L;Original exceptionprivate Throwable cause;constructor functionPublicMyException (Throwable cause) {This.cause = cause; }PublicMyException (String s,throwable cause) {Super (s);This.cause = cause; }Overloads the Printstacktrace method to print out the original exception stack informationpublic void printstacktrace () { if (cause! = null) {Cause.printstacktrace ();} super.printstacktrace ();} public void Printstacktrace (PrintStream s) { if (cause! = null) {cause.printstacktrace (s);} Super.printstacktrace (s);} public void Printstacktrace (printwriter s) { if (cause! = null) {cause.printstacktrace (s);} 
                                             
                                              super.printstacktrace (s); }}
                                             

An in-depth study and analysis of Java anomalies

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.