Re: exception handling

new topic     » topic index » view thread      » older message » newer message

Here is how exceptions are handled by C#: there is an Exception-class, and all
types of exceptions (including user-defined) inherit from the Exception-class. If
something bad happens in your code, you throw an exception like this:

if (someThingBadHappens) throw new Exception("Something bad has happened.");

If an exception occurs in a method (routine), it is thrown up to the caller of
the method. If he doesn't catch the exception, he throws it back up, and up, and
up, until someone catches it or you've reached the top. If it reaches the top, an
error-message is displayed and the program ends.

To catch an exception, you put the code you expect an exception from in a
try-catch block, like this:

StreamReader reader = null;
try
{
    reader = new StreamReader("file.txt");
    ...
}
catch(IOException ex)
{
    // an IOException occured, probably the file didn't exist
}
catch(Exception ex)
{
    // an Exception occured that I didn't expect
}
finally
{
    // close the reader
    if (reader != null) reader.Close();
}

Above you see the finally-block: this piece of code is always called, if an
exception occured or not. It's a place where you put code that really needs to be
called, like closing files or releasing resources. If you catch an exception (in
a catch-block), you can throw it back up or you could also throw a new Exception.
If you don't throw new exceptions inside the catch-block, the program doesn't
quit but just continues after the try-catch-finally-block.

In Euphoria, something like this could be used:
integer f
try
    f = open("file.txt", "r")
    c = getc(f)
    ...
catch ex -- ex could be a sequence with information
    if ex[1] = FILE_EXCEPTION then
        puts(1, ex[2]) -- s[2] could be an error message
    else
        throw ex -- unhandled exception: throw again
    end if
finally -- finally is ALWAYS called
    if f != -1 then
        close(f)
    end if
end try


--
tommy online: http://users.telenet.be/tommycarlier
Euphoria Message Board: http://uboard.proboards32.com

new topic     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu