2012-06-09 17 views
9

我正在執行我的第一個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); 
} 
+0

把裏面的'嘗試{}'塊 –

回答

13

不知道爲什麼你想在異常被捕獲後終止應用程序 - 不是爲了解決出錯的問題會更好嗎?

在任何情況下,在你的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); 
} 
+0

謝謝,這正是我正在尋找的。我明白你的意思,它可能會更好,但爲了這個項目的目的,它不需要允許錯誤修復,所以我將它保持原樣。 – Mike

9

catch塊,使用關鍵字return

catch(Exception e) 
{ 
    e.printStackTrace(); 
    return; // also you can use System.exit(0); 
} 

或者你希望把最後JOptionPane.showMessageDialogtry塊的結尾。

+0

什麼是出口之間...差(0),......退出(1)'showMessageDialog'? –

7

這是真的,回報會發生停止該程序(主要是)的執行。更一般的答案是,如果你不能在一個方法中處理特定類型的異常,你應該聲明你拋出異常,或者你應該用某種RuntimeException封裝你的異常並將它拋到更高層。 System.exit()在技術上也可以工作,但在更復雜的系統的情況下可能應該避免(您的調用者可能能夠處理異常)。

TL;博士版本:

catch(Exception e) 
{ 
    throw new RuntimeException(e); 
} 
相關問題