Black Horse programmer--java Base-exception

Source: Internet
Author: User
Tags throw exception throwable

Black Horse Programmer--java Base-Exception------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! ------- Exceptionis not normal. Abnormal conditions that occur when the program is running. is actually the problem that appears in the program. This problem is described in terms of object-oriented thinking and encapsulated as an object. Because of the cause of the problem, a problematic name, a problematic description, and many other attribute information exists. The most convenient way to have multi-attribute information is to encapsulate that information. The exception is that Java encapsulates the problem by object-oriented thinking.

Anomaly System

--------java.lang.Throwable:

Throwable: Can be thrown.

|--error: Error, in general, do not write targeted code for processing, usually the JVM occurs, you need to fix the program.

|--exception: Exceptions, can be targeted to deal with the way

Whether they are errors or exceptions, they all have specific subclasses that embody every problem, and their subclasses have a common denominator, that is, the name of the parent class as the suffix of the subclass .

All classes and objects in this system have a unique feature, which is parabolic.

The embodiment of the parabolic: the class and object in this system can be manipulated by throws and throw two key words.

Handling of exceptions

There are two kinds of processing methods: 1, capturing, 2, throwing.

1, Java provides a unique statement to handle.

Try

{

The code that needs to be instrumented.

}

catch (Exception class variable)

{

Code to handle exception (processing mode)

}

Finally

{

Statements that are bound to be executed;

}

There are three combinations of formats:

A, try

{

}

catch ()

{

}

B, try

{

}

Finally

{

}

C, try

{

}

catch ()

{

}

Finally

{

}

If an exception occurs, it is not processed, but the resource must be closed, so the try finally collection is closed only for resources.

Remember: finally is useful for the primary user to close the resource. The resource must be closed, regardless of whether an exception occurred.

system.exit (0); Exit the JVM, and only this situation is finally not executed.

When an exception occurs, when the child parent class overwrites, there are some new features

1: When a subclass overrides a method of the parent class, if the method of the parent class throws an exception, the child class's method either throws an exception or throws the parent class exception or subclass of the exception, and cannot throw other exceptions.

2: If the parent throws more than one exception, the child class can only throw a subset of the exception of the parent class when overridden.

The difference between the throw and throws keywords

Throw is used to throw an exception object, followed by an exception object, and a throw is used within a function.

Throws is used to throw exception classes, followed by the exception class name, can be followed by multiple, separated by commas. Throws is used on functions.

Generally: function content if there is a throw, throw exception object, and do not handle, then the function must be declared, otherwise the compilation fails. But there are also special cases.

Example:

The class Demo{int div (int a,int b) throws exception//the functionality of the feature via the throws keyword stating that the functionality is likely to be problematic. {return a/b;}} Class  exceptiondemo{public static void Main (string[] args) {Demo d = new Demo (); Try{int x = D.Div (4,1); 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. <span style= "White-space:pre" ></span>//The tracking information for the stack that prints the exception. }system.out.println ("Over");}}

There are two types of anomalies

1: The exception that is checked at compile time, as long as the exception and its subclasses are detected at compile time.

2: Run-time exception, where exception has a special subclass RuntimeException, and the subclass of RuntimeException is a run exception, it is said that the exception is not checked at compile time.

Differences between exceptions checked at compile time and run-time exceptions

Compile the checked exception is thrown inside the function, the function must be declared, no compilation fails.

Reason for declaration: This exception needs to be handled by the caller.

Run-time exception if thrown inside a function, no declaration is required on the function.

Not declared reason: Do not need the caller to handle, run-time exception occurs, can no longer let the program continue to run, so, do not let the call processing, directly let the program stop, by the caller to modify the code.

The benefits and principles of exceptions

Benefits:

1. Encapsulate the problem

2, the normal process code and problem-handling code to separate, easy to read.

Principle:

1. There are two kinds of processing methods: try or throws.

2, call to throw the function of the exception, throw a few, just deal with a few. A try corresponds to multiple catch.

3. When more than one catch, the parent class catch is placed at the bottom. Otherwise, the compilation will error because the rest of the catch statements are not executed.

4, in the catch, the need to define a targeted treatment. Do not simply define printstacktrace, output statements. and do not write. When the exception is caught, the feature cannot be processed and can continue to be thrown in the catch.

Custom Exceptions:

When developing, there is a problem that is not defined in Java in the project, then we need to follow the Java exception to establish the idea, the project's unique problems are also encapsulated objects. This exception, called a custom exception.

For division operations, 0 is not possible as a divisor. This problem is described in Java with the ArithmeticException class. For this function, in our project, the divisor can not be a negative number except 0. But the negative part of Java does not have a description. So we need to customize this exception.

To customize the exception steps:

1: Define a subclass to inherit exception or runtimeexception, so that the class has a parabolic nature.

2: Operate by throw or throws.

Example:

Class Fushuexception extends Exception//getmessage (); {private int value; Fushuexception () {super ();} Fushuexception (String msg,int value) {super (msg); this.value = value;} public int GetValue () {return value;}} Class Demo{int div (int a,int b) throws Fushuexception{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");}}










Black Horse programmer--java Base-exception

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.