我正在开展我的第一个
Java项目,实施一个名为“HeartRates”的课程,该课程取得用户的出生日期,并返回其最大和目标心率.主要测试程序中的一切工作除了一件事之外,我无法弄清楚在异常被捕获后如何停止打印其余的代码.
我不太确定代码中的异常被捕获的全部部分,因为它是由教授给我们复制和粘贴的.如果任何人可以告诉我如何在发生错误后终止程序,或者打印一个自定义的错误信息,并阻止程序进一步执行,我将不胜感激.
这是代码:
import java.util.Scanner; import java.util.GregorianCalendar; import javax.swing.JOptionPane; public class HeartRatesTest { public static void main(String[] args) { HeartRates test= new HeartRates(); Scanner input = new Scanner( System.in ); GregorianCalendar gc = new GregorianCalendar(); gc.setLenient(false); JOptionPane.showMessageDialog(null,"Welcome to the Heart Rate Calculator");; test.setFirstName(JOptionPane.showInputDialog("Please enter your first name: \n")); test.setLastName(JOptionPane.showInputDialog("Please enter your last name: \n")); JOptionPane.showMessageDialog(null,"Now enter your date of birth in Month/Day/Year order (hit enter after each): \n"); try{ String num1= JOptionPane.showInputDialog("Month: \n"); int m= Integer.parseInt(num1); test.setMonth(m); gc.set(GregorianCalendar.MONTH,test.getMonth()); num1= JOptionPane.showInputDialog("Day: \n"); m= Integer.parseInt(num1); test.setDay(m); gc.set(GregorianCalendar.DATE,test.getDay()); num1= JOptionPane.showInputDialog("Year: \n"); m= Integer.parseInt(num1); test.setYear(m); gc.set(GregorianCalendar.YEAR,test.getYear()); gc.getTime(); // exception thrown here } catch (Exception e) { e.printStackTrace(); } String message="Information for "+test.getFirstName()+" "+test.getLastName()+": \n\n"+"DOB: "+ test.getMonth()+"/" +test.getDay()+ "/" +test.getYear()+ "\nAge: "+ test.getAge()+"\nMax Heart Rate: "+test.getMaxHR()+" BPM\nTarget Heart Rate(range): "+test.getTargetHRLow() +" - "+test.getTargetHRHigh()+" BPM"; JOptionPane.showMessageDialog(null,message); }
解决方法
不太确定为什么要在异常被捕获后终止应用程序 – 修正错误是不是更好?
在任何情况下,在你的catch块:
catch(Exception e) { e.printStackTrace(); //if you want it. //You could always just System.out.println("Exception occurred."); //Though the above is rather unspecific. System.exit(1); }