You are on page 1of 28

EXCEPTION HANDLING

Handled by:
Harish
Amit
Rizwan
Srikant
INDEX.ITEM();
TRY{
Defintion
Types
Hierarchy
Sample Code
}
Catch(Exceptions e){
appropriateResponse
}
Finally{
Summary
}

DEFINITION
An exception is an error condition that changes the normal flow of control in a
program

An exception is an abnormal condition that occurs at run time. For example divide
by 0.

Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code.

A programmer may not foresee an exception in the program, which being not
handled may cause the system to behave distinctively.


UMMTHEN WHAT IS ERROR HANDLING??
An Error is any unexpected result obtained from a program during
execution.
Unhandled errors may manifest themselves as incorrect results or
behavior, or as abnormal program termination.
Errors should be handled by the programmer, to prevent them from
reaching the user.

TYPES OF EROR ERRR..ERROR
Some typical causes of errors:
Memory errors (i.e. memory incorrectly allocated,
memory leaks, null pointer)

File system errors (i.e. disk is full, disk has been removed)

Network errors (i.e. network is down, URL does not exist)

Calculation errors (i.e. divide by 0)
HEIRARCHY OF EXCEPTIONS

Error
Throwable
Exception
LinkageError
VirtualMachoneError
ClassNotFoundException
CloneNotSupportedException
IOException
AWTError
AWTException
RuntimeException

ArithmeticException
NullPointerException
Unchecked
Checked
NoSuchElementException

SAMPLED SAMPLE CODE
Try{
//risky code below
texting on mobile in class hours
}
Catch(Exception ex){
apologize to the teacher
}
Finally{
it depends buddy
}
A WORD OF CAUTION
Exception handling separates error-handling code from normal
programming tasks.

Thus making programs easier to read and to modify.

Be aware, however, that exception handling usually requires more
time and resources because it requires instantiating a new exception
object, rolling back the call stack, and propagating the errors to the
calling methods.

PRE-DEFINED EXCEPTIONS
Java has predefined exception classes within Java Class Library
Can place method invocation in try block
Follow with catch block for this type of exception
Example classes

BadStringOperationException
ClassNotFoundException
IOException
NoSuchMethodException

/* UNHANDLED EXCEPTION */
java.util.Scanner;
Division { public static
void main(String[] args) {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt();
b = input.nextInt();
result = a / b;
System.out.println("Result = " + result);
}
}
/* TRY */
Division {
public static void main(String[] args) {
int a, b, result;
Scanner input = new Scanner(System.in);
System.out.println("Input two integers");
a = input.nextInt(); b = input.nextInt();
try try
{ result = a / b;
System.out.println("Result = " + result); }
catch(ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
}
}
/* CATCH IF YOU CAN */
catch(ArithmeticException e) {
System.out.println("Exception caught: Division by zero.");
}
THROW, THROWS, THREW.
Throw <theCode>

We use 'throw' statement to throw an exception or simply use the throw
clause with an object reference to throw an exception.
The syntax is 'throw new Exception();'. Even you can pass the error message
to the Exception constructor.

CoDe




import java.io.FileNotFoundException;
class DemoThrowsException {
public void readFile(String file) throws FileNotFoundException { #A
if (file == null)
throw new NullPointerException(); #B
boolean found = findFile(file);
if (!found)
throw new FileNotFoundException("Missing file"); #C
else {
//code to read file
}
}
boolean findFile(String file) {
//code to return true if file can be located
}
}
THREWPHEW!!

try{
execute keyword threw
}
Catch(keywordNotFoundException e)
{
System.out.println(this keyword is purely a work of fiction
and has no resemblance to any real life keyword in java. If in
case it is somehow found, it will be regarded as sheer
coincidence);
}
Finally{
System.out.println( :W);
}
/* FINALLY SUM CODE*/
The finally block will execute whether or not an exception is thrown.

If an exception is thrown, the finally block will execute even if no catch
statement matches the exception.

This can be useful for closing file handles and freeing up any other resources
that might have been allocated at the beginning of a method with the intent
of disposing of them before returning.

The finally clause is optional. However, each try statement
requires at least one catch or a finally clause.

Now, its time to see some </code>
TYPES
Exceptions fall into two categories:

Checked Exceptions

Unchecked Exceptions
CHECKED EXCEPTION
Unlike C++, JAVA is quite strict about catching exceptions
Exceptions which are checked for during compile time are called checked
exceptions.
(all except Error, RuntimeException and their subclasses),
Java compiler forces the caller must either catch it
or explicitly re-throw it with an exception specification.
Why is this a good idea?
By enforcing exception specifications from top to bottom, Java guarantees
exception correctness at compile time.

Example: SQLException or any userdefined exception extending the
Exception class

<CHECKED CODE>
public class myexception{
public static void main(String args[]){
try{
File f = new File(myfile);
FileInputStream fis = new FileInputStream(f);
}
catch(FileNotFoundException ex){
File f = new File(Available File);
FileInputStream fis = new FileInputStream(f);
}
finally{
// the finally block
}
//continue processing here.
}

UNCHEKED EXCEPTION
Unchecked exceptions represent error conditions that are considered fatal
to program execution.

You do not have to do anything with an unchecked exception. Your
program will terminate with an appropriate error message.

The exceptions raised, if not handled will be handled by the Java Virtual
Machine. The Virtual machine will print the stack trace of the exception
indicating the stack of exception and the line where it was caused.



<SAMPLE CODE>
class Example {
public static void main(String args[])
{
int arr[] ={1,2,3,4,5};
/*My array has only 5 elements but
* I'm trying to display the value of
* 8th element. */
System.out.println(arr[7]);
}
}
TRY, TRY AND TRY AGAIN
Try{ } statements can be nested. One try block may contain another try
block
In case of nested try blocks, context of that exception is pushed onto stack.
Inner try block may/or may not have catch statements associated with it.
If an exception is thrown from inner try block then first inner catch statements
are matched (if present) . If no match is found then outer try block are
matched. If there also no match found then default handler will be invoked.
However, if outer try block throws the exception then only outer try blocks
are matched.
SO HOW DOES THIS NESTED TRY LOOKS LIKE
try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
catch(CException e) { .
}
catch(DException e) { .
}
}
catch(AException e) { . }
catch(BException e) { . }

try
{
Statement A;
Statement B;
try
{
Statement C;
Statement D;
}
}
catch(AException e) { . }
catch(BException e) { . }
catch(CException e) { . }
catch(DException e) { . }

AND HERE IS AN EXAMPLE



/*see the code*/
4\Nestedtry.java
REFERENCES
http://docs.oracle.com/javase/tutorial/essential/exceptions/
http://www.tutorialspoint.com/java/java_exceptions.html
www.javatpoint.com

THANK U

You might also like