Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception caught but program keeps running

I am working on my first Java project implementing a class called "HeartRates" which takes the user's date of birth and returns their max and target heart rate. Everything in the main test program works except for one thing, I can't figure out how to stop the rest of the code from printing after the exception is caught.

I am not really sure about the entire portion of code where the exception is caught because it was copied and pasted from what the professor gave us. If anybody can tell me how to terminate the program after an error occurs, or print a custom error message and stop the program from executing further I would appreciate it.

Here is the code:

 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);
}
like image 850
Mike Avatar asked Jun 09 '12 21:06

Mike


People also ask

Will program continue after catching exception?

The continue statement will restart the loop (as opposed to the break statement, which terminates the loop). As such if you replace break; with continue; , you will keep on looping after your Exception is caught (providing no other Exception is thrown but the one caught), ans the error message is displayed.

How do you continue a program execution even after throwing an exception?

Resuming the program When a checked/compile time exception occurs you can resume the program by handling it using try-catch blocks. Using these you can display your own message or display the exception message after execution of the complete program.

How do I continue after exception is caught?

If an exception is caught and not rethrown, the catch() clause is executed, then the finally() clause (if there is one) and execution then continues with the statement following the try/catch/finally block.

Does code execution stop when exception is thrown?

Code execution does not stop even after an exception thrown.


2 Answers

Not really sure why you want to terminate the application after the exception is caught - wouldn't it be better to fix whatever went wrong?

In any case, in your catch block:

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);
}
like image 113
Michael Avatar answered Sep 28 '22 14:09

Michael


It's true that return would happen to stop the execution of this program (being in main). The more general answer would be if you cannot handle a particular type of exception in a method, you should be either declaring that you throw said exception, or you should wrap your Exception with some kind of RuntimeException and throw that to the higher layer.

System.exit() also technically works, but in the case of a more complex system should likely be avoided (your caller may be able to handle the exception).

tl;dr version:

catch(Exception e)
{
    throw new RuntimeException(e);
}
like image 31
Charlie Avatar answered Sep 28 '22 14:09

Charlie