Menu
Topics Index
...
`


Exceptions >
Siva Nookala - 18 Mar 2016
Java supports two keywords throw and throws. throw helps in throwing a new exception or re-throwing a caught exception. throws needs to the placed after the method signature to indicate the caller of the method what exceptions a method can throw.

Railway Exceptions
class TestRailwayExceptions
{
    public static void main(String arg[])
    {
        try
        {
            String travel_date = "21/12/2012";
            TicketBooker ticketBooker = new TicketBooker();
            ticketBooker.bookTicket(17023, travel_date, 3, 1);
            System.out.println("Tickets booked successfully.");
        }
        catch(RailwayException re)
        {
            System.out.println("Railway booking failed. Reason : " + re.getErrorMessage());
        }
    
    }
}

class RailwayException extends Exception
{
    int trainNo;
    String errorMessage;
    
    RailwayException(int trainNo, String errorMessage)
    {
        this.trainNo = trainNo;
        this.errorMessage = errorMessage;
    }

    String getErrorMessage()
    {
        return errorMessage;
    }
}

class ServiceCancelledException extends RailwayException
{
    String date;

    ServiceCancelledException(int trainNo, String date)
    {
        super(trainNo, "The service of train " + trainNo + " is cancelled on " + date);
        this.date = date;
    }
}

class SeatsNotAvailableException extends RailwayException
{
    String date;

    SeatsNotAvailableException(int trainNo, String date)
    {
        super(trainNo, "There are no seats available for the train " + trainNo + " on " + date);
        this.date = date;
    }
}


class TicketBooker
{
    public void bookTicket(int trainNo, String date, int adults, int children)
        throws RailwayException // LINE A
    {

        if(isServiceCancelled(trainNo, date))
        {
            throw new ServiceCancelledException(trainNo, date); // LINE B
        }

        if(areSeatsAvailable(trainNo, date, adults, children))
        {
            confirmBooking(trainNo, date, adults, children);
        }
        else
        {
            throw new SeatsNotAvailableException(trainNo, date); // LINE C
        }
    }

    private boolean isServiceCancelled(int trainNo, String date)
    {
        // Code for checking if the service is cancelled
        return false; // LINE D
    }

    private boolean areSeatsAvailable(int trainNo, String date, int adults, int children)
    {
        // Code here for checking if the seats are available
        return false; // LINE E
    }

    private void confirmBooking(int trainNo, String date, int adults, int children)
    {
        // code here to confirm the booking
    }
}
OUTPUT

Railway booking failed. Reason : There are no seats available for the train 17023 on 21/12/2012

DESCRIPTION

Here, we have created an hierarchy of exceptions extending from the class Exception. The RailwayException extends from Exception. ServiceCancelledException and SeatsNotAvailableException extend from RailwayException. In the TicketBooker class we have created a method bookTicket which takes the trainNo, date, adults and children as parameters and books the ticket. In case the service is cancelled or if the seats are not available, then it throws appropriate exception.
As shown in the LINE B and LINE C, it uses the throw keyword for throwing an exception. And every method which throws an exception should include the throws clause in the method declaration as shown at LINE A.
In the main method we have called the bookTicket method in the try-block and written the code to catch any RailwayExceptions.

THINGS TO TRY
  • Change the return value from false to true at LINE E and see if the program runs with out exceptions and prints Tickets booked successfully.
  • Change the return value from false to true at LINE D and see if we the program throws ServiceCancelledException.
  • Create one more exception CounterClosedException which extends from RailwayException. Also create a method called isCounterClosed in the TicketBooker class and see if you can change the bookTicket method to throw the CounterClosedException when the method isCounterClosed returns true.
  • Change the main method to add separate catch blocks for SeatsNotAvailableException and ServiceCancelledException. Print a different message in these catch blocks. Also note that the catch block for RailwayException should continue to exist and it should be the last catch block, since the sub-class exceptions should be before the super-class exceptions.
  • Completely remove the try-catch block in the main method and see what compilation errors you get.
Shown above is a relatively complex program demonstrating the use of user-defined exceptions, throwing of exceptions and how to try and catch them. Please see Exception Handling Syntax In Java Programming for more details about throw and throws keywords.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.