java-Exception Handling 1

Source: Internet
Author: User

A Java exception and error level Figure 1.1 Figure 1

1.2 Figure 2

The process of two abnormal birth

The 1 exception can end the function.

It also lets the program end.

Occurrence and difference of three anomalies and errors


The problem with the Java runtime is the exception.

In Java, there are error errors in addition to exception exception that occur during runtime.

Exceptions: Typically, a targeted approach can occur. such as: Define an array arr[3], but you want to access the 4th value. Array index out of bounds
Error: There is usually no targeted processing after this occurs. such as: Define an array arr[1024*1024*1024] out of memory
Error often occurs at the system level, and is fed back to the JVM by the system in which the JVM resides.
The code cannot be corrected for processing.

3.1 Exceptions

Such as: Define an array arr[3], but you want to access the 4th value. Array index out of bounds

3.2 Error

Such as: Define an array arr[1024*1024*1024] out of memory

The simple application of four anomalies

Application of the exception:

When writing a procedure, it is important to consider the issue of the program.
Example: Selling fruit function needs to pass money parameters, there may be counterfeit currency.
So the definition program needs to consider the robustness of the program.

Add some logical judgments.

4.1 Throw the exception yourself
classdemo{/*gets the element for the given array by the given corner mark. */intGetElement (int[] arr,intindex) {/ *1 The JVM is out of the question, packing the objects and throwing them. But it does not provide enough information to force. Want to be clearer and need to write for yourself. It's thrown out not to meet our requirements. ready to throw yourself . */
Wrote it myself.
if(arr==NULL){Throw NewNullPointerException ("the array pointed to by Arr does not exist");}if(index<0|| index>=arr.length) {
2
//If this condition is satisfied, the function cannot continue the operation. At this point, you must end the feature and inform the caller of the problem. This will require an exception to be resolved. //How to use it? //1, create an exception object. Encapsulates some hint information (custom). //2, this object needs to be communicated to the caller. How to Tell? How do you pass this object to the caller? You can do this by using the keyword throw. Throw exception object;//3,throw is used within a function to throw an exception object and to end the function. Throw NewArrayIndexOutOfBoundsException ("wrong corner mark,"+index+"The index does not exist in the array");}intelement =Arr[index];returnelement;}}
Test
classExceptionDemo3 { Public Static voidMain (string[] args) {Demo d=NewDemo ();int[] arr = { the, A, the};intnum = D.getelement (NULL,2); //the array pointed to by Arr does not exist
System. out. println ("num="+num); System. out. println ("over");}}

4.2 Small Exercises

4.2.1 Problems

 Public classTest { Public Static voidMain (string[] args) {person P=NewPerson ("QQ",-5); }}classperson{PrivateString name; Private intAge ; Person (String name,intAge ) {        //Add logical judgments.         if(age<0|| Age> $) {System. out. println ("Age Value Error"); return;//terminates initialization.         }         This. Name =name;  This. Age =Age ; }    //defines the string representation corresponding to the person object. Overrides the ToString method in object.      PublicString toString () {return "person[name="+name+", age="+age+"]"; }}
Results

This can be compiled and run to see the prompt message, but the problem does not occur and the program continues to execute. and print the P object.
This is unreasonable.

4.2.2 Improvement with exception handling

Package test; Public classTest { Public Static voidMain (string[] args) {person P=NewPerson ("QQ", -5); }}classPerson {PrivateString name; Private intAge ; Person (String name,intAge ) {        //Add logical judgments.         if(Age <0|| Age > $) {            Throw NewIllegalArgumentException (age +", the age value is illegal");        //changes have taken place here }  This. Name =name;  This. Age =Age ; }    //defines the string representation corresponding to the person object. Overrides the ToString method in object.      PublicString toString () {return "person[name="+ name +", age="+ Age +"]"; }}

Results

Five exceptions for customization and Architecture 5.1 custom Exception thinking

Can you define a problem name that meets the requirements of my program?

Exception information can be customized, then the name of the exception can be defined? Can you define a reading that is more consistent with your own program?

Several of the previous exceptions are described by Java through the class. and encapsulates the problem as an object, which conforms to the object-oriented idea.
In fact, the exception is to encapsulate the problem as an object.

So I'm also going to describe the kind of problem I need.

5.2 Define and throw yourself
Package test; Public classTest { Public Static voidMain (string[] args) {person P=NewPerson ("QQ", -5); }}classnoageexception{noageexception () {} noageexception (String message) {}}classPerson {PrivateString name; Private intAge ; Person (String name,intAge ) {        //Add logical judgments.         if(Age <0|| Age > $) {            Throw NewNoageexception (age +", the age value is illegal"); }         This. Name =name;  This. Age =Age ; }    //defines the string representation corresponding to the person object. Overrides the ToString method in object.      PublicString toString () {return "person[name="+ name +", age="+ Age +"]"; }}
Results

5.3 Custom Exception plus parent class Throwable
class Noageexception extends throwable{    noageexception () {}    noageexception (String message) {}}
Results

5.4 Custom Exception plus parent class RuntimeException

plus super (message) to get results

java-Exception Handling 1

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.