08-01-2013, 11:20 AM
Exception Handling
Exception Handling.ppt (Size: 506 KB / Downloads: 97)
Exception-Handling Fundamentals
An exception is an abnormal condition that arises in a code sequence at run time
A Java exception is an object that describes an exceptional condition that has occurred in a piece of code
When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error
An exception can be caught to handle it or pass it on
Exceptions can be generated by the Java run-time system, or they can be manually generated by your code
Java exception handling is managed by via five keywords: try, catch, throw, throws, and finally
Program statements to monitor are contained within a try block
If an exception occurs within the try block, it is thrown
Code within catch block catch the exception and handle it
System generated exceptions are automatically thrown by the Java run-time system
To manually throw an exception, use the keyword throw
Any exception that is thrown out of a method must be specified as such by a throws clause
Exception Types
All exception types are subclasses of the built-in class Throwable
Throwable has two subclasses, they are
Exception (to handle exceptional conditions that user programs should catch)
An important subclass of Exception is RuntimeException, that includes division by zero and invalid array indexing
Error (to handle exceptional conditions that are not expected to be caught under normal circumstances). i.e. stack overflow
Using try and catch
Handling an exception has two benefits,
It allows you to fix the error
It prevents the program from automatically terminating
The catch clause should follow immediately the try block
Once an exception is thrown, program control transfer out of the try block into the catch block
Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism
Nested try Statements
A try statement can be inside the block of another try
Each time a try statement is entered, the context of that exception is pushed on the stack
If an inner try statement does not have a catch, then the next try statement’s catch handlers are inspected for a match
If a method call within a try block has try block within it, then then it is still nested try
Reading Console Input
Because System.in refers to an object of type InputStream, it can be used for inputStream
Putting it all together:
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
To read character from from BufferedReader, we write,
int read( ) throws IOException
It reads character from the input stream and returns it as an integer value (return –1 at the end)