寫一個方法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需要配套使用。