JAVA 18th (exceptions and thoughts (I ))

Source: Internet
Author: User

JAVA 18th (exceptions and thoughts (I ))
Exception: important knowledge points

The code for exception handling is simple, so it is important to understand its ideas.

I. Overview:

An exception is an exception that occurs during running.

Throwable


Both the Exception and Error sub-classes use the parent class name as the suffix.

Exception example: array out-of-bounds, parameter passing error...

Class Futime {} class Bigtime {} public class Main {public static void main (String [] args) {/* int [] a = new int [5]; * a = null; System. out. println (a [5]); // exception */sleep (-5);}/* public static void sleep (int t) {if (t <0) {// data error, processing method //..... for more information about the error correction, see} else if (t> 10000) {// data error, handling method // data error, handling method // data error, solution: new Bigtime ();} else {System. out. print ("break" + t + "split");} */public static void sleep (int t) // This is much clearer {if (t <0) // but there is a problem. Who is calling this function and how can I receive the exception? {// throw the new Futime (); // It indicates that the time is negative, this object contains the name, information, location, and other information} else if (t> 10000) // For example: I caught a cold {Throw new Bigtime (); // C. Take the medicine and go to the hospital ..., java can understand how to cure colds} else {System. out. print ("break" + t + "split ");}}}

*
* This reflects the differences between JAVA and c. C uses if to judge and write many solutions, while java uses
* Describes abnormal conditions and encapsulates objects.
* A class that describes abnormal conditions is called an exception class.
* The previous normal process code and problem handling code are combined
* The normal process code is now separated from the problem handling code to improve readability.
* In fact, the exception is that java encapsulates the problem into an object through the object-oriented thinking.
* Use an exception class to describe it
*
* To sum up one sentence, different classes are used for specific descriptions of different problems, such as cross-border corner labels and null pointers.
*

Ii. Exception System

If there are many problems, it means that the class described previously has many
By extracting the commonalities above, an exception system is formed.
The final problem (abnormal situations) is divided into two categories

Throwable: // whether it is an error or an exception, the problem should be thrown to let the caller know and handle it-> throwing

(There are two schools under the parent class)
1. Generally, it cannot be processed. Represented by the Error class
2. It can be processed. Use Exception

System features:
Throwable and all its sub-classes are throttled.

How can this problem be reflected?

Two keywords are used: throws and throw. All classes and objects operated by these two keywords can be throttled.
(Errors and exceptions are similar to diseases that can be cured or cannot be cured)
Error:
Feature: it is a serious problem thrown out by JVM, which has affected program running.
The occurrence of this problem is generally not targeted, because it cannot be processed, directly modify the program (int [] a = new int [1024*1024*800], open up an array of MB)

There are many direct subclasses of Exception, and there are not many direct subclasses of Error, but they are not handled, so they are rather harsh.
Features:
The suffix names of sub-classes use their parent class names as suffixes and are highly readable, such as OutOfMemoryError.

Iii. Principles and thrown exceptions


Demo:
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3ryb25np1_vcd4kpha + placement = "brush: java;"> class ExceptionDemo {public int method (int [] arr, int index) {if (arr = null) throw new NullPointerException ("How can an array reference be empty? "); If (index> = arr. length) {// return-1; why not write return, because it does not calculate throw new ArrayIndexOutOfBoundsException ("array badge out of bounds" + index ); // throw new ArrayIndexOutOfBoundsException ("" + index); // default} if (index <0) {throw new ArrayIndexOutOfBoundsException ("the array badge cannot be negative" + index);} return arr [index] ;}} public class Main {public static void main (String [] args) {int [] a = new int [10]; ExceptionDemo C = new ExceptionDemo (); int num = C. method (a, 20); // int num = C. method (null, 2); System. out. print ("num" + num );}}
Iv. custom exception classes and throws

Similar to the negative badge exception, which is not defined in java, you can customize the description based on the idea of creating a java exception, and encapsulate the called object (custom exception)

PS: If a class is called an exception class, this class must inherit the exception system. Only the child classes of the exception system can be throttled and can be operated by throw or throws.

Class FuException extends Exception {FuException () {}} // After defining an Exception, you need to inform the caller of the possible problem class ExceptionDemo {// or capture, either public int method (int [] arr, int index) throws FuException {if (index <0) {throw new FuException () ;}return arr [index] ;}} public class Main {public static void main (String [] args) throws FuException {int [] a = new int [10]; ExceptionDemo C = new ExceptionDemo (); int num = C. method (a,-2); System. out. print ("num" + num );}}

The above two throws correspond

V. Differences between exception detection and runtime exception during compilation

Exception category:

1. Exception detected during compilation: As long as Exception and its subclass are both, except the special subclass RuntimeException System
Ps: once this problem occurs, we hope to check it during compilation so that the problem can be handled in a corresponding way.

2. Do not detect exceptions during compilation (runtime exceptions): RuntimeException and its subclass-> the compiler does not detect this system at all.
Ps: this problem occurs because the function cannot continue and the operation cannot be performed. It is also caused by caller or internal status changes.
This problem is generally not handled, and is directly compiled and passed. At runtime, the program called by the caller is forced to stop and the caller can modify the code.
(Exceptions often encountered during development)

Therefore, when a custom Exception occurs, either an Exception or RuntimeException is defined.

Difference between throw and throws

1. throws are used on functions.
Throw is used in the function.
2. throws exception classes. Multiple exception classes can be thrown and separated by commas.
Throw throws an object.

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.