Java exception exercise 2 and java Exercise 2
/*
There is a circle and a rectangle
You can obtain the area. For an invalid area value, it is deemed that the obtained area is faulty.
The problem is indicated by an exception.
You must first set the program
*/
/* First think about how to write this program
Basic Attributes are mandatory.
What about area?
1. can be defined as a function
2. It can be defined as an interface.
3. database or something
*/
1 interface Shape/* can be printed directly. You can return */2 {3 void getArea ();/* do you want to pass Parameters? No, because this is an abstract class and some common attributes need to be extracted. This is not used here and must be rewritten, here you can obtain it again */4} 5 class NoValueException extends RuntimeException 6 {7 NoValueException (String message)/* constructor */8 {9 super (message ); /* call the constructor of the parent class * // * the error message of the parent class is displayed, directly assigned */10} 11} 12 class Cricle implements Shape13 {14 private int radius; 15 public static final double PI = 3.14; 16 Cricle (int radius) 17 {18 if (radius <0) 19 throw new RunTimeException ("invalid");/* use this exception name is not good, it is difficult to handle the problem, you should customize the name */20 this. radius = radius; 21} 22 public void getArea () 23 {24 System. out. println (radius * PI ); /* do not need to change the value from a name PI */25} 26} 27 28 29 class Rec implements Shape/* rectangle */30 {31 private int len, wid; /* define length and width */32 Rec (int len, int wid) /* This buddy has this item at initialization */33 {34 if (len <= 0 | wid <= 0) 35 {36 throw new NoValueException ("invalid value"); 37} 38 39 this. len = len;/* assign a value */40 this. wid = wid; 41 42} 43 public void getArea ()/* rewrite */44 {45 System. out. println (len * wid);/* print the output area directly */46} 47} 48 49 50 class predictiontext151 {52 public static void main (String args []) 53 {54 // try/* check code block */55 // {56 Rec r = new Rec (3, 4);/* you find that the input is negative and the area is negative, this is not allowed. It was previously avoided with if, but now, please use */57 r. getArea ();/* if an error occurs in the above Code, this part will not run */58 //} 59 // catch (NoValueException e)/* receive an exception, this processing is useless */60 // {61 // System. out. println (e. toString ();/* output exception information */62 //} 63 System. out. println ("over");/* final output * // * However, it is useless to run the command. It is better to directly use the runtime exception without checking the capture process, stop directly */64} 65}