2016-02-13 250 views
1

我對異常處理相當陌生,正在尋找一些特殊異常的幫助。我編寫了一個GUI程序,根據他們的生日來確定用戶的年齡。我想處理如果用戶輸入除有效生日之外的任何內容時拋出的異常。我想我已經正確地處理了拋出的異常(NumberFormatException),但堆棧跟蹤仍在顯示。有沒有辦法來防止這種情況,或者它只是拋出/捕獲異常的一部分? (我也是新來張貼在這個網站,所以我很想在我怎樣才能讓我的職位更好的任何反饋,謝謝!)Java異常處理和堆棧跟蹤

這裏是我的代碼:

/* 
This program was written to determine a users age based on the input of 
their birthday and the current date. 
Written by Randy Egan for CSC161. 
Some exception handling has been implemented when entering an invalid 
birthday. 
*/ 
import java.util.Calendar; 
import java.util.Scanner; 
import java.io.*; 
import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
public class AgeCalculator extends JFrame{ 

public static final int WIDTH = 600; 
public static final int HEIGHT = 200; 
public static final int LEFT = 450; 
public static final int RIGHT = 250; 
//these will be used to set positioning and size for the window 

private JLabel enterBDayL, userAgeL; 
private JTextField enterBDayTF, userAgeTF; 
private JButton clearB, calculateB; 
//these will be used to set up the GUI 

private Calendar cal = Calendar.getInstance(); 

public AgeCalculator(){ 

    //start of GUI setup- 

    setTitle("Age Calculator"); 

    enterBDayL = new JLabel("Enter your birthday in the form MM/DD/YYYY"); 
    userAgeL = new JLabel("Your current age is"); 

    enterBDayTF = new JTextField(); 
    userAgeTF = new JTextField(); 

    clearB = new JButton("Clear"); 
    calculateB = new JButton("Calculate"); 
    calculateB.addActionListener(new CalculateButtonHandler()); 
    clearB.addActionListener(new ClearButtonHandler()); 


    Container pane = getContentPane(); 
    pane.setLayout(new GridLayout(3,2)); 

    pane.add(enterBDayL); 
    pane.add(enterBDayTF); 
    pane.add(userAgeL); 
    pane.add(userAgeTF); 

    pane.add(clearB); 
    pane.add(calculateB); 

    setSize(WIDTH,HEIGHT); 
    setLocation(LEFT,RIGHT); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setVisible(true); 
} 

private class CalculateButtonHandler implements ActionListener{ 
//This method is where the age calculation happens 
    public void actionPerformed(ActionEvent e){ 
    String rawBirthday = enterBDayTF.getText(); 
    try{ 
     String[] birthday = rawBirthday.split("/"); 
     int birthMonth = Integer.parseInt(birthday[0]); 
     int birthDay = Integer.parseInt(birthday[1]); 
     int birthYear = Integer.parseInt(birthday[2]); 
    } 

    catch(NumberFormatException x){ 
     System.err.println("Invalid Birthday Format: " + x); 
     enterBDayTF.setText(""); 
     userAgeTF.setText(""); 
     JOptionPane.showMessageDialog(null, "Please enter a birthday in the form MM/DD/YYYY"); 
    } 
     String[] birthday = rawBirthday.split("/"); 
     int birthMonth = Integer.parseInt(birthday[0]); 
     int birthDay = Integer.parseInt(birthday[1]); 
     int birthYear = Integer.parseInt(birthday[2]); 

    int currentDay = cal.get(Calendar.DAY_OF_MONTH); 
    int currentMonth= cal.get(Calendar.MONTH); 
    currentMonth++; 
    //The current month has to be incremented because in this library 
    //they count the months starting from 0. Without incrementing the 
    //month, the program works perfectly fine, except for birthday's 
    //in the current month, where the age is not calculated properly. 

    int currentYear = cal.get(Calendar.YEAR); 

    if(currentYear == birthYear) 
     userAgeTF.setText("" + 1); 
     //this checks to see if the user's birth year is equal to the 
     //current year, if it is, it returns one for the user's age 
     //since the user's birthday would have already passed. 

    if(currentMonth < birthMonth){ 
     int age = currentYear - birthYear - 1; 
     userAgeTF.setText("" + age); 
    } 
    if(currentMonth > birthMonth){ 
     int age = currentYear - birthYear; 
     userAgeTF.setText("" + age); 
    } 
    if(currentMonth == birthMonth && currentDay < birthDay){ 
     int age = currentYear - birthYear - 1; 
     userAgeTF.setText("" + age); 
    } 
    if(currentMonth == birthMonth && currentDay >= birthDay){ 
     int age = currentYear - birthYear; 
     userAgeTF.setText("" + age); 
    } 
    //this block of if statements is used to handle if the user's birthday 
    //has passed for the current year or not. 


    } 
} 

private class ClearButtonHandler implements ActionListener{ 
    public void actionPerformed(ActionEvent e){ 
    userAgeTF.setText(""); 
    enterBDayTF.setText(""); 
    } 
} 



public static void main(String[] args){ 
    AgeCalculator ac = new AgeCalculator();  

} 

} 
+0

異常來自行號82. Integer.parseInt函數。由於這是一個運行時異常,因此編譯器不會強迫你捕捉它。 –

+0

嘿蘭迪,歡迎來到SO!你的帖子看起來不錯,只有我想指出的是試着發佈一個MCVE(http://stackoverflow.com/help/mcve)。這意味着只有發佈相關代碼才能讓人們更快地解決您的問題,而無需對我們不需要的所有內容進行排序。例如,在這種情況下,所有的JButton和圖形對象看起來都可能不需要用於問題的目的,所以它們可以被刪除。 –

+0

非常感謝您的信息! –

回答

0

的問題是,你正在處理這個異常,但是你的代碼繼續假定提供了有效的日期。

在 AgeCalculator $ CalculateButtonHandler.actionPerformed(AgeCalculator.java:82)

移動抓後的代碼在嘗試中。如果沒有要分割的文本,則不能分割文本。

修正方法:

public void actionPerformed(ActionEvent e) { 
    String rawBirthday = enterBDayTF.getText(); 
    try { 
     String[] birthday = rawBirthday.split("/"); 
     int birthMonth = Integer.parseInt(birthday[0]); 
     int birthDay = Integer.parseInt(birthday[1]); 
     int birthYear = Integer.parseInt(birthday[2]); 

     int currentDay = cal.get(Calendar.DAY_OF_MONTH); 
     int currentMonth = cal.get(Calendar.MONTH); 
     currentMonth++; 
     //The current month has to be incremented because in this library 
     //they count the months starting from 0. Without incrementing the 
     //month, the program works perfectly fine, except for birthday's 
     //in the current month, where the age is not calculated properly. 

     int currentYear = cal.get(Calendar.YEAR); 

     if (currentYear == birthYear) 
      userAgeTF.setText("" + 1); 
     //this checks to see if the user's birth year is equal to the 
     //current year, if it is, it returns one for the user's age 
     //since the user's birthday would have already passed. 

     if (currentMonth < birthMonth) { 
      int age = currentYear - birthYear - 1; 
      userAgeTF.setText("" + age); 
     } 
     if (currentMonth > birthMonth) { 
      int age = currentYear - birthYear; 
      userAgeTF.setText("" + age); 
     } 
     if (currentMonth == birthMonth && currentDay < birthDay) { 
      int age = currentYear - birthYear - 1; 
      userAgeTF.setText("" + age); 
     } 
     if (currentMonth == birthMonth && currentDay >= birthDay) { 
      int age = currentYear - birthYear; 
      userAgeTF.setText("" + age); 
     } 
     //this block of if statements is used to handle if the user's birthday 
     //has passed for the current year or not. 

    } catch (NumberFormatException x) { 
     System.err.println("Invalid Birthday Format: " + x); 
     enterBDayTF.setText(""); 
     userAgeTF.setText(""); 
     JOptionPane.showMessageDialog(null, "Please enter a birthday in the form MM/DD/YYYY"); 
    } 
} 

的是要記住的是,在嘗試處理字符串時拋出異常。如果字符串不能被處理,因爲它不遵循所需的模式,那麼你必須處理後面的邏輯,就好像你不能繼續。