我寫了一段代碼,我想在拋出異常後繼續運行。 這裏是我的代碼:在java中拋出異常後繼續運行程序
public class SquareEquationException extends Exception{
public SquareEquationException(){
super("roots are not real numbers");
}
public static void SquareEquation() throws SquareEquationException{
double a,b,c,sqr;
int flag;
Scanner in = new Scanner(System.in);
System.out.println("enter ax^2:");
a=in.nextDouble();
System.out.println("enter bx:");
b=in.nextDouble();
System.out.println("enter c:");
c=in.nextDouble();
sqr=((b*b)-(4*a*c));
if(sqr<0)
throw new SquareEquationException();
else{
sqr=Math.sqrt(sqr);
double x1=(-b+sqr)/(2*a);
double x2 = (-b-sqr)/(2*a);
if(x1==x2)
System.out.println("root is:" + x1);
else
System.out.println("x1 is:"+x1 +"\n"+ "x2 is:"+x2);
}
System.out.println("enter 1 to continue or any key to exit");
flag = in.nextInt();
while(flag==1){
System.out.println("enter ax^2:");
a=in.nextDouble();
System.out.println("enter bx:");
b=in.nextDouble();
System.out.println("enter c:");
c=in.nextDouble();
sqr=((b*b)-(4*a*c));
if(sqr<0){
throw new SquareEquationException();
}
else{
sqr=Math.sqrt(sqr);
double x1=(-b+sqr)/(2*a);
double x2 = (-b-sqr)/(2*a);
if(x1==x2)
System.out.println("root is:" + x1);
else
System.out.println("x1 is:"+x1 +"\n"+ "x2 is:"+x2);
}
System.out.println("enter 1 to continue or any key to exit");
flag=in.nextInt();
}
}
public static void main(String[] args) throws SquareEquationException{
SquareEquation();
}
}
我怎能菜單/程序運行時拋出異常後? 菜單工作:如果用戶程序插入1繼續運行,否則程序退出。
使用try catch語句和異常處理 – Stultuske
你'Exeption'填充通過'main'方法,因此你的程序中止。你需要「抓住」這個例外並採取相應的行動。如果發生「異常」,立即停止執行,並輸入第一個匹配的「catch」塊。有關更多信息,您可能需要查看[關於異常的Oracle蹤跡](https://docs.oracle.com/javase/tutorial/essential/exceptions/)。 – Turing85