Hey all I am currently a java beginner and I would like to ask how would I return control to my main if ever I encounter an exception created by me?

For example:

public void checkIn(int roomNumber, String occupantName, int day)
            throws ExceptionHandler {
        int checkValue = this.employingHotel.checkIn(roomNumber, occupantName, day);

        switch (checkValue) {
            case -5:
                throw new ExceptionHandler ("Inexistent Room for Check In");
            case -6:
                throw new ExceptionHandler ("Occupant Already Exists");
            default:
                break;
        }
    }

This code here returns an exception whenever an error is found within the underlying classes of this method's owner. So when I run my program I see in the output that after it displays an exception it does not run the other parts of the code in my main, which is what I didn't want to happen.

I've still got a little bit of processing down my main and I would like to perform those processes along with printing of other details from them.

So how do I return control back to my main whilst recognizing this error?

And lastly, based on something I googled earlier, I created this exception handling class.

public class ExceptionHandler extends Exception {

    public ExceptionHandler(String message) {
        super(message);
    }

}

This is supposed to handle all the errors in my package, but I feel a bit uneasy about this class because, I think exceptionhandler codes are not this simple? I mean are they just simply for outputting error messages? or am I grasping the requirement of "create an exception class for your project" concept wrong? I really think I am missing something here.

Thank you all.

EDIT:

I would also like to add that, I am not entirely sure if we should have an exception handler class of our own in our programs. I am just assuming we should since we just tackled this lesson last week, but we also took up simple try catch statements, so I am now thinking that what if I can just handle my errors with simple try catch clauses and put in my catch statements a simple System.out.println(<Error message here>) so that my execution of main wouldn't be interrupted?

Recommended Answers

All 10 Replies

The idea is that if your method may have errors it can't deal with it should throw some kind of Exception. There's nothing to stop you throwing one of the Exceptions that are defined in the Java API, but it's far more helpful to define a new Exception type of your own that makes it perfectly clear what's happening. That is what the code for "ExceptionHandler" does, although its name is very bad - this isn't a handler, it's just a custom Exception type. It would be better to call it something like CheckInException.
Then in your main you can use try/catch to deal with these CheckInExceptions like you said in your EDIT:

Thank you for the reply, so how do I go about making my own exceptionhandler if mine is just an err error message displayer class haha.

An exception handler is basically just a catch clause that does whatever you need to deal with the exception when it is thrown. Just displaying an error message is a good start. After that you may want to go back and try again with new input, or whatever.

Method 1 calls method 2 from inside a try block
Method 2 throws an exception
Method 1 catches exception in a catch clause
Catch block does something appropriate - this is the exception handler.

So if I understand correctly, I do not specifically have to create a class for an exception handler but just use appropriately, try catch clauses to create an "exception handler" is that it?

If it is, then why do people still create custom exception handling classes if they can insert all the handling along with the original source code by placing the try catch clauses in it?

You may be confusing "creating an exception handler class" with "creating an exception class". I haven't seen examples of people creating a class just to handle an exception (except for a couple of very complex distributed apps), but it's normal to create a new exception class when you perform error checking and want to throw an exception that shows exactly what kind of error it was (eg CheckInException for errors in your checkIn method).

Ahh, I guess I am confusing them both. Can you please enlighten me what is their difference? they both sound synonymous to me in a sense that an exception handler class and an exception class is both used just to display errors (e.g. my sample exceptionhandler class).

Or are they just to be used as triggers within my try statements so that I can catch the exceptions? and in that sense, should I create separate classes for each and every exception in my code or could I do something like this:

public class ExceptionHandler extends Exception {
    private final string error1 = "error 1 message here";
    private final string error2 = "error 2 message here";
    private final string error3 = "error 3 message here";

    public ExceptionHandler(int errorCode) {
        if (errorCode == 1) {
         super(error1);
        }
        else if (errorCode == 2){.... } // and so on
    }

}

that way I can crate a "general exception class" for each and everyone of my errors.

An Exception is basically a data structure used to transmit information about an error from the source of the error back up to a calling program. An Exception handler is a piece of code that catches and deals with an Exception (eg prints an error message). The Exception class may have methods that the handler can use, eg to print the stack trace, but the specific handler has to decide whether and when to use those methods.
The code you just posted seems way over the top. All you need is

public class CheckInException extends Exception {
    public CheckInException (String message) {
        super(message);
    }
}

In your checkIn method you can then just say:

if (some error has been detected) 
  throw new CheckInException("Some suitable error description");

Then any code that calls your method can simply catch(CheckInException e) {...
to handle the Exception as it choses.

ps
The code that throws the exception knows that a problem has happened, but doesn't know what is the right thing to do about it - eg it doesn't know whether it's been called from a console app (so the message should go to System.out), or a Swing GUI (in which case it needs an error dialog box), or a web server (send the message as an HTML page). This is also true of the Exception class itself.
The calling program (try/catch exception handler) doesn't know the details of how the problem was detected, but it does know the context in which it is running, and therefore how to display it, so it just needs to get the error message text from the Exception so it can display it appropriately

commented: Muchos helpful :) +2

thanks for your tip, I implemented this on my own code and it works wonderfully, I named my exception class as a GeneralException and passed messages as needed. Thank you :D

OK, that's great.
The one suggestion I would make is that you give your Exception a more specific name.
Think about someone else reading your code - what will they learn when they see

// do stuff
catch (GeneralException...

as opposed to

// do stuff
catch (UnableToBookRoomException ...

It's really hard to read other people's code and understand what they were trying to achieve. Good naming can make a huge difference.
J

I see, so I should have made a: CheckInException, CheckOutException, since this is a hotel simulation program. Thanks again! :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.