Tuesday, November 23, 2010

CoolTuts - Java - Exceptions

An exception is a point in the code where something out of the ordinary has happened and the regular flow of the program needs to be interrupted; an exception is not necessarily an error. A method which has run into such a case will throw an exception using the throw (ExceptionClass) method. When an exception is thrown it must be caught by a catch statement that should sit right after a try statement.
How to handle an Exception?
To handle an Exception, enclose the code that is likely to throw an exception in a try block and follow it immediately by a catch clause.
Exception handling is a very powerful tool, you can use it to catch and throw exceptions and thus group all your error handling code very well and make it much more readable in larger more complex applications. After the try section there must exist one or more catch statements to catch some or all of the exceptions that can happen within the try block. Exceptions that are not caught will be passed up to the nexxt level, such as function that called the one which threw the exception, and so on.
try
{
// code that might fail
}
catch(Exception1ThatcanHappen E)
{
}
catch(Exception2ThatcanHappen E)
{
//things to do if this exception was thrown.
}

No comments:

Post a Comment