异常的实例

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;
	}
}
  • 3
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值