Home

Throwing Exceptions

 

Exception Throwing

 

Introduction

Imagine you write a program that requests a studentís age from the user. As we know, everybodyís age is positive. Therefore, we need to figure out what to do if the user types a negative number. The expression that checks whether the number entered is positive can be written as:

if(studentAge < 0)

If the condition is true, the minimum you can do is to send the produced error away.

Practical LearningPractical Learning: Introducing Exception Throwing

  1. Start NetBeans and create a Java Application named bcr3
  2. Change the file as follows:
     
    package bcr3;
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            long employeeNumber = 0;
            String employeeName;
            double hourlySalary = 0.00;
            double weeklyTime = 0.00;
            double regularTime, overtime;
            double regularPay, overtimePay, netPay;
            
            try {
                System.out.print("Enter Employee Number (00000): ");
                employeeNumber = scnr.nextLong();
            }
            catch(Exception eim) {
                System.out.println(eim.getMessage());
            }
    
            if( employeeNumber == 82500 )
                employeeName = "Helene Mukoko";
            else if( employeeNumber == 92746 )
                employeeName = "Raymond Kouma";
            else if( employeeNumber == 54080 )
                employeeName = "Henry Larson";
            else if( employeeNumber == 86285 )
                employeeName = "Gertrude Monay";
            else
                employeeName = "Unknown";
                    
            System.out.print("Enter Hourly Salary: ");
            hourlySalary = scnr.nextDouble();
            
            System.out.print("Enter Weekly Time: ");
            weeklyTime = scnr.nextDouble();
    
            if(weeklyTime  < 40 ) {
                regularTime = weeklyTime;
                overtime = 0;
                regularPay = hourlySalary * regularTime;
                overtimePay = 0;
                netPay = regularPay;
            }
            else {
                regularTime = 40;
                overtime = weeklyTime - 40;
                regularPay = hourlySalary * 40;
                overtimePay = hourlySalary * overtime;
                netPay = regularPay + overtimePay;
            }
                
            System.out.println("======================");
            System.out.println("=//= BETHESDA CAR RENTAL =//=");
            System.out.println("==-=-= Employee Payroll =-=-==");
            System.out.println("-------------------------------------------");
            System.out.printf("Employee #:    %d\n", employeeNumber);
            System.out.printf("Employee Name: %s\n", employeeName);
            System.out.printf("Hourly Salary: %.2f\n", hourlySalary);
            System.out.printf("Weekly Time:   %.2f\n", weeklyTime);
            System.out.printf("Regular Pay:   %.2f\n", regularPay);
            System.out.printf("Overtime Pay:  %.2f\n", overtimePay);
            System.out.printf("Total Pay:     %.2f\n", netPay);
            System.out.println("======================");
        }
    }
  3. To execute the exercise, press F6
  4. Enter the Employee number as 82500, the hourly salary as 22.35, and the weekly hours as 38.50, then press Enter
     
    Enter Employee Number (00000): 82500
    Enter Hourly Salary: 22.35
    Enter Weekly Time: 38.50
    ==============================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    ------------------------------
    Employee #:    82500
    Employee Name: Helene Mukoko
    Hourly Salary: 22.35
    Weekly Time:   38.50
    Regular Pay:   860.48
    Overtime Pay:  0.00
    Total Pay:     860.48
    ======================

Throwing an Exception

To throw an exception, you use the throw keyword. The primary formula of using this keyword is:

try {
    Normal flow

    When to throw the exception
	throw What?
}
catch(Exception e) {
    // Deal with the exception here
}

The new keyword in this formula is throw. On the right side of throw, indicate to the compiler what to do. This means that the throw keyword is followed by an expression. We will see various examples.

In our introduction to exceptions, we got acquainted with the Exception class. Besides the default constructor, the Exception class is equipped with another constructor that takes a string as argument. When using the throw keyword, you can use this constructor to specify a message to display to display in case of an error. To do this, use the new operator to call the constructor and pass a message to it. Here is an example:

import java.util.Scanner;

public class Exercise {

    public static void main(String[] args) {
	int studentAge = 0;
	Scanner scnr = new Scanner(System.in);

	try {
	    System.out.print("Student Age: ");
	    studentAge = scnr.nextInt();

	    if( studentAge < 0 )
		throw new Exception("Positive Number Required");
	    System.out.println("Student Age: " + studentAge);
	}
	catch(Exception exc)
	{
	    System.out.println("Error: " + exc.getMessage());
	}
    }
}

This program starts with the try block that asks the user to enter a positive number. If the user enters an invalid value, the program examines the throw keyword. This throw appears to display a string. The compiler registers this string and since there was an exception, the program exits the try block (it gets out of the try block even if the rest of the try block is fine) and looks for the first catch block it can find. If it finds a catch that does not take an argument, it would still use the catch. Otherwise, you can use the catch block to display the error string that was sent by the throw keyword.

Practical LearningPractical Learning: Throwing an Exception

  1. To throw an exception, change the Main.java file as follows:
     
    public class Main {
    
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            long employeeNumber = 0;
            String employeeName;
            double hourlySalary = 0.00;
            double weeklyTime = 0.00;
            double regularTime, overtime;
            double regularPay, overtimePay, netPay;
            
            try {
                System.out.print("Enter Employee Number (00000): ");
                employeeNumber = scnr.nextLong();
            
                if( employeeNumber < 0 )
                    throw new Exception("The employee number must be positive");
            }
            catch(Exception exc) {
                System.out.println(exc.getMessage());
            }
    
            . . . No Change
        }
    }
  2. Execute the application
  3. When asked to enter the employee number, enter -22446688 and press Enter
  4. Enter the hourly salary as 22.35, and the weekly hours as 42.50, then press Enter
     
    Enter Employee Number (00000): -22446688
    The employee number must be positive
    Enter Hourly Salary: 22.35
    Enter Weekly Time: 42.50
    ======================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    -------------------------------------------
    Employee #:    -22446688
    Employee Name: Unknown
    Hourly Salary: 22.35
    Weekly Time:   42.50
    Regular Pay:   894.00
    Overtime Pay:  55.88
    Total Pay:     949.88
    ======================

Catching Multiple Exceptions

The programs we have seen so far dealt with a single exception. Most of the time, a typical program will use different types of errors. Fortunately, you can deal with as many errors as possible. To do this, you can create a catch block for each (type of) error. The formula to follow is:

try {
	Code to Try
}
catch(Arg1)
{
	One Exception
}
catch(Arg2)
{
	Another Exception
}

The compiler would proceed in a top-down as follows:

  1. The compiler enters the try block and follows the normal flow of the program
  2. If no exception occurs in the try block, the rest of the try block is executed.
    If an exception occurs in the try block, the try displays a throw expression that specifies the type of error that happened.
    1. The compiler gets out of the try block and examines the first catch
    2. If the first catch does not match the thrown error, the compiler switches to the next catch. This continues until the compiler finds a catch that matches the thrown error.
    3. If one of the catches matches the thrown error, its body executes. If no catch matches the thrown error, you have (or the compiler has) two alternatives. If there is no catch that matches the error (which means that you did not provide a matching catch), the compiler hands the program flow to the operating system. Another alternative is to include a catch whose argument is the Exception default constructor. The catch(Exception) is used if no other catch, provided there was another, matches the thrown error. The catch(Exception), if included as part of a catch clause, must always be the last catch, unless it is the only catch of the clause.

Multiple catches are written if or when a try block is expected to throw different types of errors. Imagine a program that requests some numbers from the user and performs some operation on the numbers. Such a program can be written as follows:

import java.util.*;

public class Exercise {

    public static void main(String[] args) {
	byte studentAge = 0;
	Scanner scnr = new Scanner(System.in);

	try {
	    System.out.print("Student Age: ");
	    studentAge = scnr.nextByte();

	    if( studentAge < 0 )
		throw new Exception("Positive Number Required");

	    System.out.println("Student Age: " + studentAge);
	}
	catch(InputMismatchException exc) {
	    System.out.println("The operation could not be carried because " +
                               "the number you typed is not valid");
	}
	catch(Exception exc)
	{
	    System.out.println("Error: " + exc.getMessage());
	}
    }
}

Practical LearningPractical Learning: Catching Multiple Exceptions

  1. To catch multiple exceptions, change the Main.java file as follows:
     
    . . . No Change
    
    public class Main {
    
        public static void main(String[] args) {
            . . . No Change
            
            try {
                System.out.print("Enter Employee Number (00000): ");
                employeeNumber = scnr.nextLong();
            
                if( employeeNumber < 0 )
                    throw new Exception("The employee number must be positive");
            }
            catch(InputMismatchException excim) {
                System.out.println("Invalid Employee Number");
            }
            catch(Exception exc) {
                System.out.println(exc.getMessage());
            }
    
            . . . No Change
        }
    }
  2. Execute the application
  3. When asked to enter the values, enter anything and press Enter each time

Nesting Exceptions

Like a conditional statement or a class, you can create one exception inside of another. This is referred to as nesting an exception.

Practical LearningPractical Learning: Nesting Exceptions

  1. To nest exceptions, change the Main.java file as follows:
     
    package bcr3;
    import java.util.*;
    
    public class Main {
    
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            long employeeNumber = 0;
            String employeeName;
            double hourlySalary = 0.00;
            double weeklyTime = 0.00;
            double regularTime, overtime;
            double regularPay, overtimePay, netPay;
            
            try {
                System.out.print("Enter Employee Number (00000): ");
                employeeNumber = scnr.nextLong();
            
                if( employeeNumber < 0 )
                    throw new Exception("The employee number must be positive");
    
                if( employeeNumber == 82500 )
                    employeeName = "Helene Mukoko";
                else if( employeeNumber == 92746 )
                    employeeName = "Raymond Kouma";
                else if( employeeNumber == 54080 )
                    employeeName = "Henry Larson";
                else if( employeeNumber == 86285 )
                    employeeName = "Gertrude Monay";
                else
                    employeeName = "Unknown";
                    
                try {
                    System.out.print("Enter Hourly Salary: ");
                    hourlySalary = scnr.nextDouble();
            
                    if( hourlySalary < 0 )
                        throw new Exception("The hourly salary must be positive");
                }
                catch(InputMismatchException excim) {
                    System.out.println("Invalid Hourly Salary");
                }
                catch(Exception exc) {
                    System.out.println(exc.getMessage());
                }
                
                try {
                    System.out.print("Enter Weekly Time: ");
                    weeklyTime = scnr.nextDouble();
            
                    if( weeklyTime < 0 )
                        throw new Exception("The weekly time must be positive");
                }
                catch(InputMismatchException excim) {
                    System.out.println("Invalid Weekly Time");
                }
                catch(Exception exc) {
                    System.out.println(exc.getMessage());
                }    
    
                if(weeklyTime  < 40 ) {
                    regularTime = weeklyTime;
                    overtime = 0;
                    regularPay = hourlySalary * regularTime;
                    overtimePay = 0;
                    netPay = regularPay;
                }
                else {
                    regularTime = 40;
                    overtime = weeklyTime - 40;
                    regularPay = hourlySalary * 40;
                    overtimePay = hourlySalary * overtime;
                    netPay = regularPay + overtimePay;
                }
                
                System.out.println("======================");
                System.out.println("=//= BETHESDA CAR RENTAL =//=");
                System.out.println("==-=-= Employee Payroll =-=-==");
                System.out.println("-------------------------------------------");
                System.out.printf("Employee #:    %d\n", employeeNumber);
                System.out.printf("Employee Name: %s\n", employeeName);
                System.out.printf("Hourly Salary: %.2f\n", hourlySalary);
                System.out.printf("Weekly Time:   %.2f\n", weeklyTime);
                System.out.printf("Regular Pay:   %.2f\n", regularPay);
                System.out.printf("Overtime Pay:  %.2f\n", overtimePay);
                System.out.printf("Total Pay:     %.2f\n", netPay);
                System.out.println("======================");
            }
            catch(InputMismatchException excim) {
                System.out.println("Invalid Employee Number\n" + 
                                   "The application will stop");
            }
            catch(Exception exc) {
                System.out.println(exc.getMessage());
            }
        }
    }
  2. Execute the application
  3. Enter the employee number as 54080, the hourly salary as 18.50, and the weekly time as 36.00:
     
    Enter Employee Number (00000): 54080
    Enter Hourly Salary: 18.50
    Enter Weekly Time: 36.00
    ======================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    -------------------------------------------
    Employee #:    54080
    Employee Name: Henry Larson
    Hourly Salary: 18.50
    Weekly Time:   36.00
    Regular Pay:   666.00
    Overtime Pay:  0.00
    Total Pay:     666.00
    ======================
  4. Execute the application again
  5. Enter the employee number as -54080 and press Enter
     
    Enter Employee Number (00000): -54080
    The employee number must be positive
  6. Execute the application again
  7. Enter the employee number as Can't remember and press Enter:
     
    Enter Employee Number (00000): 
    Can't remember
    Invalid Employee Number
    The application will stop
  8. Execute the application again
  9. Enter the employee number as 22468, the hourly salary as Minimum Wage, and press Enter:
     
    Enter Employee Number (00000): 22468
    Enter Hourly Salary: Minimum Wage
    Invalid Hourly Salary
    Enter Weekly Time: Invalid Weekly Time
    ======================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    -------------------------------------------
    Employee #:    22468
    Employee Name: Unknown
    Hourly Salary: 0.00
    Weekly Time:   0.00
    Regular Pay:   0.00
    Overtime Pay:  0.00
    Total Pay:     0.00
    ======================
 
     
 

Exceptions and Methods

 

Introduction

One of the most effective techniques used to deal with code is to isolate assignments. We learned this with methods. Here are examples:

import java.util.Scanner;

public class Exercise {
    private static double getSide() {
	double side;
	Scanner scnr = new Scanner(System.in);

        System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	return side;
    }

    private static void show(double side) {
        System.out.println("\nSquare Characteristics");
        System.out.printf("Side:      %.2f\n", side);
        System.out.printf("Perimeter: %.2f\n", side * 4);
    }

    public static void main(String[] args) {
	double squareSide = getSide();
	show(squareSide);
    }
}

Here is an example of running the program:

Square Processing
Enter Side: 22.50

Square Characteristics
Side:      22.50
Perimeter: 90.00

Inside of any method, you write code for exception handling, just as we have done so far. Here is an example:

import java.util.Scanner;

public class Exercise {
    private static double getSide() {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

        System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	return side;
    }

    private static void show(double side) {
	try {
	    System.out.println("\nSquare Characteristics");
            System.out.printf("Side:      %.2f\n", side);
            System.out.printf("Perimeter: %.2f\n", side * 4);
	}
	catch(Exception e) {
	    System.out.println("The operation could not be completed!");
	}
    }

    public static void main(String[] args) {
	double squareSide = getSide();
	show(squareSide);
    }
}

Here is an example of running the program:

Square Processing
Enter Side: 14.55

Square Characteristics
Side:      14.55
Perimeter: 58.20

Here is another example of running the same program:

Square Processing
Enter Side: 2se
Exception in thread "main" java.util.InputMismatchException
        at java.util.Scanner.throwFor(Unknown Source)
        at java.util.Scanner.next(Unknown Source)
        at java.util.Scanner.nextDouble(Unknown Source)
        at Exercise.getSide(Exercise.java:11)
        at Exercise.main(Exercise.java:32)

One of the ways you can use methods in exception handling is to have a central method that dispatches assignments to other methods. The other methods can use the values of variables; for example they can test. If an exception occurs, the other method can display a message or throw an exception. This throwing can be picked up by the central method that sent the variable. The method that originated the trying can hand it to a catch block or one of the catch blocks in the calling method that can handle the exception. This means that you can create a method that only throws an exception but does not necessarily deal with it. Here is an example of such a method:

import java.util.*;

public class Exercise {
    private static double getSide() {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	if( side < 0 )
	    throw new InputMismatchException("Positive number required");

	return side;
    }

    public static void main(String[] args) {
	
    }
}

Notice that the above getSide() method signals that an exception could be thrown and it even specifies the type of exception. If you write this type of method that is only prepared to throw an exception, you must prepare the method that calls it to handle the exception. To do this, in the calling method, create exception handling code and include a catch block that can handle the type of the exception thrown. Here is an example:

import java.util.*;

public class Exercise {
    private static double getSide() {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	if( side < 0 )
	    throw new InputMismatchException("Positive number required");

	return side;
    }

    private static void show(double side) {
	System.out.println("\nSquare Characteristics");
        System.out.printf("Side:      %.2f\n", side);
        System.out.printf("Perimeter: %.2f\n", side * 4);
    }

    public static void main(String[] args) {
	try {
	    double squareSide = getSide();
	    show(squareSide);
	}
	catch(InputMismatchException exc) {
	    System.out.println(exc.getMessage());
	}
    }
}
 

A Method that Throws an Exception

Notice that in the above program, besides main(), there are two methods; one throws an exception, the other does not. Besides writing code that throws an exception, to indicate to the compiler that a method is throwing an exception, after it closing parenthesis, type the throws keyword followed by the class name of the type of exception that will be thrown. Here is an example:

import java.util.*;

public class Exercise {
    private static double getSide() throws InputMismatchException {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	if( side < 0 )
	    throw new InputMismatchException("Positive number required");

	return side;
    }

    private static void show(double side) {
	try {
	    System.out.println("\nSquare Characteristics");
            System.out.printf("Side:      %.2f\n", side);
            System.out.printf("Perimeter: %.2f\n", side * 4);
	}
	catch(Exception e) {
	    System.out.println("The operation could not be completed!");
	}
    }

    public static void main(String[] args) {
	try {
	    double squareSide = getSide();
	    show(squareSide);
	}
	catch(InputMismatchException exc) {
	    System.out.println(exc.getMessage());
	}
    }
}

In reality, even if a method does not explicitly throw an exception, you can still include a throws InputMismatchException expression to it if you want, in anticipation to a bad behavior. Here is an example:

import java.util.*;

public class Exercise {
    private static double getSide() throws InputMismatchException {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	if( side < 0 )
	    throw new InputMismatchException("Positive number required");

	return side;
    }

    private static void show(double side) throws InputMismatchException {
	System.out.println("\nSquare Characteristics");
        System.out.printf("Side:      %.2f\n", side);
        System.out.printf("Perimeter: %.2f\n", side * 4);
    }

    public static void main(String[] args) {
	try {
	    double squareSide = getSide();
	    show(squareSide);
	}
	catch(InputMismatchException exc) {
	    System.out.println(exc.getMessage());
	}
    }
}

In the above code, the throws InputMismatchException expression is option. In reality, there is a rule you must follow. If a method has code that throws a general exception of type Exception, you must add a throws Exception expression to it. If you violate this rule, the program will not compile. For example, the following code will fail:

import java.util.*;

public class Exercise {
    private static double getSide() {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	if( side < 0 )
	    throw new Exception("Positive number required");

	return side;
    }

    public static void main(String[] args) {
	
    }
} 

This would produce:

Exercise.java:13: unreported exception java.lang.Exception; must be caught or de
clared to be thrown
            throw new Exception("Positive number required");
            ^
1 error

The solution is to include a throws Exception expression to it: 

import java.util.*;

public class Exercise {
    private static double getSide() throws Exception {
	double side = 0;
	Scanner scnr = new Scanner(System.in);

	System.out.println("Square Processing");
        System.out.print("Enter Side: ");
        side = scnr.nextDouble();

	if( side < 0 )
	    throw new Exception("Positive number required");

	return side;
    }

    private static void show(double side) throws InputMismatchException {
	System.out.println("\nSquare Characteristics");
        System.out.printf("Side:      %.2f\n", side);
        System.out.printf("Perimeter: %.2f\n", side * 4);
    }

    public static void main(String[] args) {
	try {
	    double squareSide = getSide();
	    show(squareSide);
	}
	catch(Exception exc) {
	    System.out.println(exc.getMessage());
	}
    }
}

Practical LearningPractical Learning: Handling Exceptions in Methods

  1. To nest exceptions, change the Main.java file as follows:
     
    package bcr3;
    import java.util.*;
    
    public class Main {
    
        private static double requestHourlySalary() throws InputMismatchException {
            double salary = 0.00;
            Scanner scnr = new Scanner(System.in);
    
            try {
                System.out.print("Enter Hourly Salary: ");
                salary = scnr.nextDouble();
            }
            catch(InputMismatchException excim) {
                System.out.println("Invalid Hourly Salary");
            }
            catch(Exception exc) {
                System.out.println(exc.getMessage());
            }
            
            return salary;
        }
        private static double requestWeeklyTime()  throws InputMismatchException {
            double time = 0.00;
            Scanner scnr = new Scanner(System.in);
                
            try {
                System.out.print("Enter Weekly Time: ");
                time = scnr.nextDouble();
            }
            catch(InputMismatchException excim) {
                System.out.println("Invalid Weekly Time");
            }
            catch(Exception exc) {
                System.out.println(exc.getMessage());
            }    
            
            return time;
        }
            
        private static void displayPayroll(long employeeNumber,
                                           String employeeName, 
                                           double hourlySalary, 
                                           double weeklyTime, 
                                           double regularPay, 
                                           double overtimePay, 
                                           double netPay) {
            
                System.out.println("======================");
                System.out.println("=//= BETHESDA CAR RENTAL =//=");
                System.out.println("==-=-= Employee Payroll =-=-==");
                System.out.println("-------------------------------------------");
                System.out.printf("Employee #:    %d\n", employeeNumber);
                System.out.printf("Employee Name: %s\n", employeeName);
                System.out.printf("Hourly Salary: %.2f\n", hourlySalary);
                System.out.printf("Weekly Time:   %.2f\n", weeklyTime);
                System.out.printf("Regular Pay:   %.2f\n", regularPay);
                System.out.printf("Overtime Pay:  %.2f\n", overtimePay);
                System.out.printf("Total Pay:     %.2f\n", netPay);
                System.out.println("======================");
        }
        
        public static void main(String[] args) {
            Scanner scnr = new Scanner(System.in);
            long employeeNumber = 0;
            String employeeName;
            double hourlySalary = 0.00;
            double weeklyTime = 0.00;
            double regularTime, overtime;
            double regularPay, overtimePay, netPay;
            
            try {
                System.out.print("Enter Employee Number (00000): ");
                employeeNumber = scnr.nextLong();
            
                if( employeeNumber < 0 )
                    throw new Exception("The employee number must be positive");
    
                if( employeeNumber == 82500 )
                    employeeName = "Helene Mukoko";
                else if( employeeNumber == 92746 )
                    employeeName = "Raymond Kouma";
                else if( employeeNumber == 54080 )
                    employeeName = "Henry Larson";
                else if( employeeNumber == 86285 )
                    employeeName = "Gertrude Monay";
                else
                    employeeName = "Unknown";
                
                hourlySalary = requestHourlySalary();
                if( hourlySalary < 0 )
                    throw new Exception("The hourly salary must be positive");
                
                weeklyTime = requestWeeklyTime();
                if( weeklyTime < 0 )
                    throw new Exception("The weekly time must be positive");
            
                if(weeklyTime  < 40 ) {
                    regularTime = weeklyTime;
                    overtime = 0;
                    regularPay = hourlySalary * regularTime;
                    overtimePay = 0;
                    netPay = regularPay;
                }
                else {
                    regularTime = 40;
                    overtime = weeklyTime - 40;
                    regularPay = hourlySalary * 40;
                    overtimePay = hourlySalary * overtime;
                    netPay = regularPay + overtimePay;
                }
                
                displayPayroll(employeeNumber, employeeName,
                               hourlySalary, weeklyTime,
                               regularPay, overtimePay,
                               netPay);
            }
            catch(InputMismatchException excim) {
                System.out.println("Invalid Employee Number\n" + 
                                   "The application will stop");
            }
            catch(Exception exc) {
                System.out.println(exc.getMessage());
            }
        }
    }
  2. Execute the application
  3. Enter the employee number as 86285, the hourly salary as 25.85, and the weekly time as 42.50:
     
    Enter Employee Number (00000): 86285
    Enter Hourly Salary: 25.85
    Enter Weekly Time: 42.50
    ======================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    -------------------------------------------
    Employee #:    86285
    Employee Name: Gertrude Monay
    Hourly Salary: 25.85
    Weekly Time:   42.50
    Regular Pay:   1034.00
    Overtime Pay:  64.63
    Total Pay:     1098.63
    ======================
  4. Execute the application again
  5. Enter the employee number as 92746 and press Enter
  6. Enter the hourly salary as Company Will Decide and press Enter
  7. Enter the weekly time as Check Time Sheet and press Enter
     
    Enter Employee Number (00000): 92746
    Enter Hourly Salary: 
    Company Will Decide
    Invalid Hourly Salary
    Enter Weekly Time: 
    Check Time Sheet
    Invalid Weekly Time
    ======================
    =//= BETHESDA CAR RENTAL =//=
    ==-=-= Employee Payroll =-=-==
    -------------------------------------------
    Employee #:    92746
    Employee Name: Raymond Kouma
    Hourly Salary: 0.00
    Weekly Time:   0.00
    Regular Pay:   0.00
    Overtime Pay:  0.00
    Total Pay:     0.00
    ======================

 

 
 
 
   
 

Previous Copyright © 2009-2012, FunctionX, Inc. Next