如何创建自定义异常
public class Myexception extends Exception{
public MyException(String ErrorMessage){
super(ErrorMessage);
}
}
自定义异常的抛出与捕获
public class Main
{
static int avg(int a,int b)throws MyException
{
if(a>100||b>100)
{
throw new MyException("数值太大了");
}
if(a<0||b<0)
{
throw new MyException("不可以使用负数");
}
return (a+b)/2;
}
public static void main(String[] args) {
try
{
int result1=avg(123,125);
System.out.println(result1);
}catch (MyException a)
{
System.out.println(a);
}
}
}
结果:MyException: 数值太大了