Exercises:
1. Calculate the area of the circle, the radius cannot be zero and negative
Packagecom.oracle.Demo01;PublicClassDemo02 { //Write a method for calculating the area of a circle, passing a radius, returning an areaPublicStaticvoidMain (string[] args) {Double s=0; s = Area (-4); System.out.println (s);}PublicStaticdouble area (double r) { Span style= "COLOR: #0000ff" >try {if (R<=0" {throw new runtimeexception (); //runtimeexception run exception, does not declare, does not handle exception, directly error and stops }} catch (Exception e) {// TODO auto-generated catch Block E.printstacktrace (); } double s=math.pi*r*R; return S;}}
2. Average, parameter cannot be negative
Packagecom.oracle.Demo01;ImportJava.util.Scanner;PublicClassDemo03 {//Now to create an exception class that detects negative numbers, throws an exception if it is a positive numberPublicStaticvoidMain (string[] args) {/*Double s=0; s = Area (9); System.out.println (s);*///Enter any parameter to find the averageDouble S=avg (1,9,6,5,2); System.out.println (s); }PublicStaticDouble Area (DoubleR) {if (r<=0){ThrowNew Fushuexception ("You passed a negative number");//Report an exception and pass a custom string}Double s=math.pi*r*Rreturn S;} // method for averaging public static double avg (double...arr) {double sum=0; for (double I:arr) {if (I<0throw new fushuexception ("parameter is negative" i; } return sum/arr.length;}}
Custom Fushuexecption class:
Package com.oracle.Demo01; custom class exception, inherited from Run exception extendsSuper(MES);}}
3. Detection age can not be negative and more than 200 years of age
Test class:
Packagecom.oracle.Demo01;PublicClassDemo04 {Public static void main (string[] args) throws Noagesexception {method ("Yi", 110); } public static void method (String name,int age) throws noagesexception{person P=new person (name,age); if (P.getage () <0| | P.getage () >200throw new noagesexception ("Invalid Age value" p.getage ())}}
Person class:
Packagecom.oracle.Demo01;PublicClassperson {PrivateString name;PrivateIntAge Person () {} person (String name,IntAge) {This.name=Namethis.age=age;} public String GetName () { Return name; public void SetName ( String name {this.name = name;} public int Getage () { returnpublic void setage (int< Span style= "COLOR: #000000" > age) {this.age =
Custom Noageexecption class:
Package com.oracle.Demo01; Class extendsSuperSuper(MES);}}
Java Learning (Exception class exercises)