题目:
写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,c “不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。
代码:
package 异常;
import java.util.*;
public class judgment {
void triangle(int a,int b,int c) throws Exception
{
if((a+b)>c&&(a+c)>b&&(c+b)>a)
System.out.println("能构成三角形");
else
throw new Exception();
}
}
package 异常;//有错
import java.util.*;
public class Test {
public static void main(String[] args) {
Scanner in =new Scanner(System.in);
int x,y,z;
System.out.println("请输入边长:");
judgment j=new judgment();
try
{ x=in.nextInt();
y=in.nextInt();
z=in.nextInt();
j.triangle(x,y,z);
}
catch(InputMismatchException e1)
{
System.err.println("请输入整数");
}
catch(Exception e)
{
System.err.println("不能构造三角形");
}
finally{
System.out.print("感谢使用本程序!");
}
}
}
结果:
总结:如果用方法调出异常,则需要在方法头上加
throws Exception
方法内部加throw
另外 throw 与catch需要配套使用。