/*
There is a circle and a rectangle
Can be obtained area, for area, if illegal value appears, the problem is considered to get area
The problem is represented by an exception.
First of all, the basic setup of this program
*/
/* First think about how to write this program
The basic attribute is definitely needed
To find the area?
1. Can be defined as a function
2. Can be defined as an interface
3. Or a database or something.
*/
1 InterfaceShape/*can be printed directly, can return*/2 {3 voidGetarea ();/*Do you want to pass parameters? No, because this is an abstract class, you need to extract some of the common attributes, there is no, need to rewrite, here re-fetch can*/4 }5 classNovalueexceptionextendsruntimeexception6 {7Novalueexception (String message)/*constructor Function*/8 {9 Super(message);/*calling the constructor of the parent class*/ /*here is the error message of the parent class, which can be assigned directly to the*/Ten } One } A classCricleImplementsShape - { - Private intradius; the Public Static Final Doublepi=3.14; -Cricle (intradius) - { - if(radius<0) + Throw NewRuntimeException ("illegal");/*Use this exception name is not good, do not handle the problem, you should customize the name*/ - This. radius=radius; + } A Public voidGetarea () at { -System.out.println (RADIUS*RADIUS*PI);/*do not need to change the value of a name PI*/ - } - } - - in classRecImplementsShape/*Rectangular*/ - { to Private intLen,wid;/*define length and width*/ +Rec (intLenintWid/*This guy has this thing when it's initialized.*/ - { the if(len<=0| | Wid<=0) * { $ Throw NewNovalueexception ("Illegal value appears");Panax Notoginseng } - the This. Len=len;/*to assign a value*/ + This. wid=wid; A the } + Public voidGetarea ()/*to rewrite*/ - { $System.out.println (LEN*WID);/*Direct Print output area*/ $ } - } - the - classExceptionText1Wuyi { the Public Static voidMain (String args[]) - { Wu //try/* Detect code block * / - //{ AboutRec r=NewRec (3,4);/*you find the input negative, the area is negative, which is not allowed, previously with if to avoid, but now, please use*/ $R.getarea ();/*If there is an error in the above code, the block will not run.*/ - //} - //catch (novalueexception e)/* Receive exception, this processing is useless */ - //{ A //System.out.println (e.tostring ()); /* Output Exception information * / + //} theSystem.out.println ("over");/*Final Output*/ /*However, running this is no use, it is better to directly use the runtime exception, do not need to check the capture processing, directly stop*/ - } $}
Java Exception Exercise 2