Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Exception Handling

  1. Jan 9, 2008 #1
    Hey Everyone,

    I have a question regarding exception handling. First I'll explain what I know (or at the very least, what I believe I know) about exceptions just to be sure I have an idea of what's going on, then present the question.

    To let any calling methods know that a certain method might throw a certain exception, you use a throws clause in the method signature. For example:

    public void doSomething( ) throws someException
    {
    code...;
    code...;
    throw new someException;​
    }


    Also, note that in the method body, a new instance of someException is created, and then thrown to the calling routine. In this particular case, the doSomething method does not care about handling the exception, it just passes the exception to what code called it.


    Now, you could also handle exceptions in the same method in which the exception occurs by using what is known as a try block. For example

    public void doSomething( )
    {
    code...;
    code...;
    try
    {
    code...;
    throw new someException;​
    }
    catch (myException)
    {
    code...;
    code...; ​
    }
    catch (someException)
    {
    code...;
    code...;​
    }​
    }


    The code in the try block may or may not throw a new someException. However, in case it does, there is a catch statement that could handle the exception. In the event an exception does occur, the exception is caught, and control is returned to the code immediately after the last catch statement.

    Finally, my question is: Why is it that in some try blocks and method signatures with a throws clause there is no code to create and throw a new exception object? How can code like the following be legal?

    public void myMethod() throws myException
    {
    }


    or

    try
    {
    code...;​
    }


    If someone could explain this to me, or refer me to a site explaining why this is acceptable, it would be greatly appreciated. Thanks
     
  2. jcsd
  3. Jan 9, 2008 #2

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    It means the exception is going to be caught by a caller further up the tree, it is allowed in some languages and is very common in python.

    It is used when there is nothing the inner function can do about the error.
    eg. If you have a set of deeply nested functions that do network stuff and the network fails the top level GUI layer could handle the exception and tell the user. You don't want to have error message boxes coded deep in a netowkr layer.
     
  4. Jan 9, 2008 #3
    I'm sorry, but I'm still a beginner programmer, so I don't quite understand your answer. If you could dumb that down for a noob like me that would be great. Thanks.
     
  5. Jan 9, 2008 #4

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    If you don't catch an exception in a function it will get passed to the calling function and ,if that doesn't handle it, upward to the function that called that and so on. If it reaches the top of your program without being caught the OS will catch it and ussually put up an error. This is one of the big advantages of exceptions over other error correction.

    Suppose you are many functions deep in a complicated algorithm which needs to say grab some memory, open a file or talk to the network. If these fail you trigger an exception - often there is nothing the function can do about this so it passes the exception back up to a function that can do something.
    Possibly the caller can do something to fix the error (eg. free some memory) but if it can only send an error to the user - you don't want the internal functions of some algorithm eg. a sort routine, to put up an error message because then you have to include the graphics calls make it specific to one window system and it might one day be used in a system with no screen.

    Another common technique is to handle only errors you can deal with (eg out of memory) and pass on others that you can't (eg file not found)
     
  6. Jan 9, 2008 #5

    DaveC426913

    User Avatar
    Gold Member

    Yes, as others point out, there are two types of errors: ones that can be handled internally by the method and ones that can't.

    There are expected errors: in an appendtologfile method, you might throw an error if there is no log file present. This is not a problem - log files are often purged and deleted by users. Your method has no trouble with this, in fact it's routine, all it need do is create a new log file and append to it.

    Your appendtologfile method might also be unable to open the file for writing - say the user is currently viewing it. So it simply creates a new file with a different name, adding a "-b" and continues on.

    This is all meant to happen invisibly. The appendtofile operation doesn't have to alert anyone else (such as the user) that anything's wrong.


    But what if the appendtologfile encounters a problem it can't deal with? What if it's a critical operation? Say it runs into an out of memory error?

    It needs to alert someone - it needs to "pass the buck to its boss" i.e. pass its error out to whatever function called it. This is when you use the Try{} but don't include a Catch{}. So the appendtologfile method fails and the error is thrown, but it is not caught. The error automatically "bubbles up" to the function that called appendtologfile .

    function doHousekeeping(){
    try
    appendtologfile()
    morehousekeeping operations()
    catch
    alertUser("Housekeeping failed!")
    }


    In the above code, if a simple file is missing, then appendtologfile handles it gracefully and doHousekeeping continues as normal. But if appendtologfile() throws an error, doHousekeeping catches it and aborts the rest of its script to handle the error.

    You need to do this because, if well-designed, the appendtologfile should have no access to the user interface**, it only has access to its calling function (in the above case "doHousekeeping"). dohousekeeping has to decide what to do when writetologfile encounters a problem it can't deal with.

    **appendtologfile is "ecapsulated", meaning it only has knowledge of the things it absolutely need to know about - and the user interface is not one of them. This is good design.
     
    Last edited: Jan 9, 2008
  7. Jan 9, 2008 #6

    -Job-

    User Avatar
    Science Advisor

    I think most of the stuff has been covered by already by Dave and mbg, but in your first example (which i assume is from Java) the function signature indicates that it may throw a specific exception (even though it does not throw the exception itself) because it's required to.

    For example, in Java if you're doing some common file IO, such as read/write a file, if the code for reading/writing to the file does not handle an IO exception in a catch statement, then the compiler will complain (because those IO methods are marked as able to throw IO exceptions). The alternative is to not handle the exception but instead mark your function as able to throw an IO exception, so it'll just pass the exception along.

    In Java you're required to have at least one catch or finally clause. The finally takes place after the exception has been reported and is commonly used to clean up resources (close files/connections).
     
    Last edited: Jan 9, 2008
  8. Jan 10, 2008 #7
    Hmm. I'm familiar with C# instead of Java or Python. It might be helpful in understanding the general concept to note that in C# there isn't any specification within method signatures concerning exceptions. Instead, it's assumed that any method can throw an exception of any type and you can have multiple catch blocks after the try for different exception types.
     
  9. Jan 11, 2008 #8

    mgb_phys

    User Avatar
    Science Advisor
    Homework Helper

    Specifing the exceptions that can be thrown in Java was supposed to allow for formal verification of programs. It never really caught on because it's too complicated in the real world - but you have to document what can be thrwon somewhere so you might as well do it in the class defn.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?