作为Java初学者,为了巩固自己学习的Java异常处理,故分享一个Java中自定义异常的范例吧!
同时也方便自己的学习整理!
package AAA;
import java.util.Scanner;
public class NoPositiveIntegerException extends Exception{
public NoPositiveIntegerException(String msg){
super(msg);
}
}
//对自定义异常的测试类
class MyExceptionApp{
//定义的方法中显示抛出异常
public static double circleSquare(int r)throws NoPositiveIntegerException{
if(r <= 0)
throw new NoPositiveIntegerException("输入数字不是正整数!");
return (Math.PI*r*r);
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.println("请输入正整数:");
int radius = sc.nextInt();
try{
System.out.print("圆的面积为:" + circleSquare(radius));
}catch (NoPositiveIntegerException e){
System.out.println("发生的自定义异常:" + e.getMessage());
}
}
}