Exception
An exception is a problem that occurs during the execution of a program and disturbs the normal flow of execution.
It can occur due to following reasons:
- A user has entered invalid data.
- A file that needs to be opened cannot be found.
- A network connection has been lost in the middle of communications, or the JVM has run out of memory.
Types of Exceptions:
- Checked exceptions:
- Typically a user error or a problem that cannot be foreseen by the programmer.
- For example, if a file is to be opened, but the file cannot be found, an exception occurs.
- These exceptions cannot simply be ignored at the time of compilation.
- Must be handled using try catch block and throws clause with method declaration.
- User Exception.
- Runtime exceptions:
- The exceptions that probably could have been avoided by the programmer.
- Runtime exceptions are ignored at the time of compilation.
- No need to declare with throws clause.
- Example division by zero and invalid array indexing.
- Programmer Exception.
- Errors:
- The problems that arise beyond the control of the user or the programmer.
- Errors are typically ignored in code because one can rarely do anything about an error.
- For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
- Hardware Exception.
- Runtime exception and Errors together called as unchecked exception as they need not to be checked at compile time.
Exception Hierarchy:
Unchecked RuntimeException Subclasses:
· ArithmeticException : Arithmetic error, such as divide-by-zero.
· ArrayIndexOutOfBoundsException: Array index is out-of-bounds.
· ArrayStoreException: Assignment to an array element of an
incompatible type.
· ClassCastException: Invalid cast.
· IllegalArgumentException: Illegal argument used to invoke a method.
· IndexOutOfBoundsException: Some type of index is out-of-bounds.
· NegativeArraySizeException: Array created with a negative size.
Java’s Checked Exceptions
· ClassNotFoundException: Class not found.
· CloneNotSupportedException: Attempt to clone an object that does not implement the Cloneable interface.
· IllegalAccessException: Access to a class is denied.
· InstantiationException: Attempt to create an object of an abstract class or interface.
· InterruptedException: One thread has been interrupted by another thread.
· NoSuchFieldException: A requested field does not exist.
· NoSuchMethodException: A requested method does not exist.
Handling Exception:
If an exception occurs that is not caught anywhere, the program will terminate and print a message to the console, giving the type of the exception and a stack trace.
To catch an exception, you set up a try/catch block. The simplest form of the try block is as follows:
try
{
code
more code
more code
}
catch (ExceptionType e)
{
handler for this type
}
* If any of the code inside the try block throws an exception of the class specified in the catch clause, then
1. The program skips the remainder of the code in the try block;
2. The program executes the handler code inside the catch clause.
* If none of the code inside the TRy block throws an exception, then the program skips the catch clause.
* If any of the code in a method throws an exception of a type other than the one named in the catch clause, this method exits immediately. (Hopefully, one of its callers has already coded a catch clause for that type.)
Catching Multiple Exceptions
You can catch multiple exception types in a try block and handle each type differently. You use a separate catch clause for each type as in the following example:
try
{
code that might throw exceptions
}
catch (MalformedURLException e1)
{
handler code for malformed URLs
}
catch (UnknownHostException e2)
{
handler code for unknown hosts
}
catch (IOException e3)
{
handler code for all other I/O problems
}
Re-throwing and Chaining Exceptions
You can re throw an exception in a catch clause. Typically, you do this because you want to change the exception type.
Eg:
try
{
code causes exception
}
catch (SQLException e) // new exception object created and re thrown in catch block.
{
throw new ServletException("database error: " + e.getMessage());
}
The finally Clause
* When your code throws an exception, it stops processing the remaining code in your method and exits the method.
* This is a problem if the method has acquired some local resource that only it knows about and if that resource must be cleaned up.
* The code in the finally clause executes whether or not an exception was caught.
Eg:
try
{
// 1
code that might throw exceptions
// 2
}
catch (IOException e)
{
// 3
show error dialog
// 4
}
finally
{
// 5
code which will be executed regardless of exception occurs or not.
}
The throws clause
When you write your own methods, you don't have to advertise every possible throwable object that your method might actually throw. To understand when (and what) you have to advertise in the throws clause of the methods you write, keep in mind that an exception is thrown in any of the following four situations:
1. You call a method that throws a checked exception, for example, the FileInputStream constructor.
2. You detect an error and throw a checked exception with the throw statement (we cover the tHRow statement in the next section).
3. You make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException.
4. An internal error occurs in the virtual machine or runtime library.
If either of the first two scenarios occurs, you must tell the programmers who will use your method about the possibility of an exception. Why? Any method that throws an exception is a potential death trap. If no handler catches the exception, the current thread of execution terminates.
User Defined Exception Classes
Step 1: Create an exception class (extend exception class or child class of exception)
class MyException extends Exception
{
public Exception(String msg)
{
super(msg);
}
}
Step 2: Throw your very own exception type.
String readData(BufferedReader in) throws MyException
{
. . .
while (. . .)
{
if (ch == -1) // EOF encountered
{
if (n < len)
throw new MyException ();
}
. . .
}
return s;
}
No comments:
Post a Comment