1.编写一个异常类MyException,再编写一个类Student,该类有一个产生异常的方法speak(int m)。要求参数m的值大于1000时,方法抛出一个MyException对象。最后编写主类,在主方法中创建Student对象,让该对象调用speak()方法。
public class Brunt {
public static void main(String args[]){
Student stu = new Student();
try {
stu.speak(1500);
} catch (MyException e) {
e.printStackTrace();
}
}
}
public class MyException extends Exception {
public MyException(String ErrorMessagr) {
super(ErrorMessagr);
}
}
public class Student {
public void speak(int m) throws MyException{
if(m > 1000){
throw new MyException("参数太大了");
}
}
}
2.创建类Number,通过类中的方法count可得到任意两个数相乘的结果,并在调用该方法的主方法中使用try-catch语句捕捉可能发生的异常。
public class Brunt {
public static int count(int m,int n){
return m * n;
}
public static void main(String args[]) throws Exception{
try{
int result = count(12315,57876876);
System.out.println(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
3.创建类Computer,该类中有一个计算两个数的最大公约数的方法,如果向该方法传递负整数,该方法就会抛出自定义异常。
public class Computer {
public static int getMaxComm(int m , int n) throws MyException{
if( m <= 0 ||n<=0){
throw new MyException("传递的参数不是正整数");
}
if(m < n){
int temp = 0;
temp = m;
m = n;
n = temp;
}
int r = m % n;
while(r!=0){
m = n;
n = r;
r = m % n;
}
return n;
}
public static void main(String[] args) {
try {
int m = 122 , n= 0;
int reslut = getMaxComm(m,n);
System.out.println(m+" 和 "+n+"的最大共约数是:"+reslut);
} catch (MyException e) {
e.printStackTrace();
}
}
}
public class MyException extends Exception {
String message;
public MyException(String ErrorMessagr) {
message = ErrorMessagr;
}
public String getMessage(){
return message;
}
}