Java exception handling mechanism try-catch-finally

Source: Internet
Author: User
Tags define exception finally block getmessage throwable try catch

Java has a powerful exception handling mechanism, the recent initial study, the feeling of content is still quite a lot of, hereby to write their own understanding to share with you.


First, in Java code, because of the use of the MyEclipse IDE, you can automatically alert users to errors and provide a way to modify them. in many cases, when we call a method, we are prompted that a statement should be wrapped up with a try-catch statement. But has not been to understand this is why!!! Examples are as follows:


Exceptiondemo.java

Package Com.package2;class demo{int Div (int a,int b) throws exception//the functionality of the throws keyword is declared to be problematic. {return a/b;}} public class  exceptiondemo{public static void Main (string[] args) {Demo d = new Demo (); Try{int x = D.Div (4,0); System.out.println ("x=" +x); catch (Exception e)//exception e = new ArithmeticException (); {System.out.println ("except 0)"; System.out.println (E.getmessage ());  //by zero; System.out.println (E.tostring ());//Exception Name: Exception information. E.printstacktrace ();//exception name, exception information, where the exception occurred. In fact, the JVM default exception handling mechanism is to call the Printstacktrace method. Prints trace information for the stack of exceptions. }system.out.println ("Over");}}
Why is there a hint? The reason is that the method being called throws an exception, that is, declaring that this function might be an exception.

the int div (int a,int b) throws exception//is functionally declared by the throws keyword that the feature is likely to be problematic.
{
return a/b;
}

An exception is thrown here, where any call to this function is prepared to catch and handle the exception at any time.

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        Second, the exception: is the program in the run when the abnormal situation.


Exception Origin: The problem is also a specific thing in real life, can also be described in the form of Java classes. and encapsulated into objects.
In fact, Java is a description of the abnormal situation after the object.

The problem is divided into two kinds: one is a serious problem, a non-serious one.

For serious, Java is described by the error class.
For error, it is generally not written in a targeted code to handle it.

For and non-critical, Java is described by the exception class.
For exception, you can use a targeted processing method for processing.

Both error and exception have some common content.
For example: abnormal information, causes of the cause and so on.

Throwable
|--error
|--exception

Any exception or error is inherited from the Throwable class, and there are more than n seed classes in the error and exception below.


Handling of Exceptions:

(1), Java provides a unique statement to handle.

Try
{
Code that needs to be detected;
}
catch (Exception class variable)
{
Code to handle exception (processing mode)
}
Finally
{
Statements that are bound to be executed;
}

Where a statement in a try produces an exception, an exception object is thrown and assigned to this variable in the statement catch ( exception class variable ).


Since the exception is caught, the program will no longer execute the code underneath the exception, and jump directly to the bottom of the try-catch-finally statement block to begin execution. Therefore, code that executes in a finall{} statement block is typically a release program resource, such as closing an open file .


Where, in the try-catch-finally block, the finally block will not be executed in the following cases.

(1) An exception occurred in the finally block.

(2) The program is dead on the thread.

(3) in the previous code with System.exit (); (PS this is a regular occurrence)

(4) Shutdown of the CPU



(2), where catch statements are used to catch and handle exceptions, common processing mechanisms are:getMessage () toString (), and the Printstacktrace () method

Examples are as follows:

The above code, after running as follows:



Due to exception handling, the program executes and "over" is printed. If you do not add exception handling, the JVM will error and the program will stop executing. It can be seen that the default exception handling mechanism is to call the E.printstacktrace () method and terminate the execution of the program.


third, the treatment of multiple anomalies.

(1), when declaring an exception, it is recommended to declare a more specific exception. This can be handled more concretely.
(2), the other side declares a few exceptions, corresponding to a few catch blocks. Do not define an extra catch block.
If an inheritance relationship occurs in multiple catch blocks, the parent exception catch block is placed at the bottom.

Examples are as follows:

Package Com.package2;class demo{int Div (int a,int b) throws arithmeticexception,arrayindexoutofboundsexception// It is possible that the feature may be problematic by declaring the function with the throws keyword. {int[] arr = new Int[a]; System.out.println (Arr[4]); return a/b;}} Class  exceptiondemo{public static void Main (string[] args) {Demo d = new Demo (); Try{int x = D.Div (4,0); System.out.println ("x=" +x); catch (ArithmeticException e) {System.out.println (e.tostring ()); System.out.println ("was 0 except!!");} catch (ArrayIndexOutOfBoundsException e) {System.out.println (e.tostring ()); SYSTEM.OUT.PRINTLN ("angle mark out of bounds!! ");} catch (Exception e) {System.out.println ("Hahah:" +e.tostring ());} System.out.println ("Over");}}

When A=4,b=1 is passed in, the result of the run is as follows:


When A=5,b=0 is passed in, the result of the run is as follows:



Four, Custom Exceptions:


Because there are unique problems in the project, these problems are not described and encapsulated by Java. So for these unique problems you can follow the idea of Java encapsulation of problems. will be peculiar to the problem. Customize the Exception Pack.

Examples are as follows:
Requirements: In this program, for the divisor is-1, also considered to be wrong is unable to perform the operation
. then you need to have a custom description of the problem.

When a throw throws an exception object inside the function, the corresponding processing action must be given. Either in-house try catch processing. It is either declared on the function to be handled by the caller.

In general, there is an exception in the function, the function needs to be declared, you will find the result of printing only the name of the exception, but there is no exception information. Because the custom exception does not define the information.

How do you define exception information?
Because the operation of the exception information has been completed in the parent class. So as long as the subclass is constructed, the exception information is passed to the parent class through the Super statement. The custom exception information can then be obtained directly from the GetMessage method.


Focus!!! Custom exceptions must be custom class inheritance exception.

Inheritance Exception reason
: The exception system has one feature: because both the exception class and the exception object are thrown. They all have the ability to be parabolic. This parabolic feature is unique to the throwable system.

The code is as follows:

Package com.package2;//Custom Exception Classes class Fushuexception extends Exception//getmessage (); {private int value;//is an empty construction method Fushuexception () {super ();} Construction method Fushuexception (String msg,int value) {super (msg); this.value = value;}    A member method of the custom exception class used to define the exception information. public int GetValue () {return value;}} Class Demo{int div (int a,int b) throws fushuexception{//increase the judging condition if (b<0) throw new Fushuexception ("There is a case where the divisor is negative------/by Fushu ", b);//Manually throw a custom exception object through the Throw keyword. return a/b;}} Class  exceptiondemo{public static void Main (string[] args) {Demo d = new Demo (); Try{int x = D.Div (4,-9); System.out.println ("x=" +x); catch (Fushuexception e) {System.out.println (e.tostring ()); System.out.println ("divisor appears negative"); SYSTEM.OUT.PRINTLN ("The negative number of the error is:" +e.getvalue ());} System.out.println ("Over");}}
Operation Result:



V.the difference between throws and throw:
Throws is used on functions. Throw is used within a function.
Throws followed by the exception class, you can follow multiple, separated by commas. The throw is followed by an exception object.


Vi. differences between runtime exceptions and compile-time exceptions:

A: run-time exception : Just throw an exception inside the method. The method is called where no processing is done. That is, the program is planning to let the program with the runtime exception stop running .

compile-time exception : When the method is defined, the exception needs to be thrown on the method body. At the point where the method is called, you must do the appropriate exception handling, which is to select either capture or throw (throws). That is, the program can continue to execute.



                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

Java exception handling mechanism try-catch-finally

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.