continuing execution after an exception is thrown in java

DannyD picture DannyD · Mar 22, 2012 · Viewed 106.6k times · Source

I'm trying to throw an exception (without using a try catch block) and my program finishes right after the exception is thrown. Is there a way that after I throw the exception, to then continue execution of my program? I throw the InvalidEmployeeTypeException which I've defined in another class but I'd like the program to continue after this is thrown.

    private void getData() throws InvalidEmployeeTypeException{

    System.out.println("Enter filename: ");
    Scanner prompt = new Scanner(System.in);

    inp = prompt.nextLine();

    File inFile = new File(inp);
    try {
        input = new Scanner(inFile);
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        System.exit(1);
    }

    String type, name;
    int year, salary, hours;
    double wage;
    Employee e = null;


    while(input.hasNext()) {
        try{
        type = input.next();
        name = input.next();
        year = input.nextInt();

        if (type.equalsIgnoreCase("manager") || type.equalsIgnoreCase("staff")) {
            salary = input.nextInt();
            if (type.equalsIgnoreCase("manager")) {
                e = new Manager(name, year, salary);
            }
            else {
                e = new Staff(name, year, salary);
            }
        }
        else if (type.equalsIgnoreCase("fulltime") || type.equalsIgnoreCase("parttime")) {
            hours = input.nextInt();
            wage = input.nextDouble();
            if (type.equalsIgnoreCase("fulltime")) {
                e = new FullTime(name, year, hours, wage);
            }
            else {
                e = new PartTime(name, year, hours, wage);
            }
        }
        else {


            throw new InvalidEmployeeTypeException();
            input.nextLine();

            continue;

        }
        } catch(InputMismatchException ex)
          {
            System.out.println("** Error: Invalid input **");

            input.nextLine();

            continue;

          }
          //catch(InvalidEmployeeTypeException ex)
          //{

          //}
        employees.add(e);
    }


}

Answer

manub picture manub · Mar 22, 2012

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/