Download Exception Handling

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Java Basics
Exception Handling
Topics To Be Covered
• Objective
• Exception Handling
• Summary
Objectives
At the end of this course,
you will be able to understand:
• Exception Handling
Exception Handling
Exception Handling
• A built in mechanism for trapping & handling
runtime errors
• Usually deals with abnormal events or code
execution which prevents the program from
continuing, like:
– Array out of bounds accesses
– Divide by Zero
– Null pointers & so on...
www.prolearninghub.com
Exception Handling
• An exception is an event, which occur during the
execution of a program that disrupt the normal
flow of a program’s instruction.
• Exception handling in java
• When error occur the program through an
exception, when it through the system attempts to
handle it. There are verity of methods to handle
this. The list of methods is known as call stack.
www.prolearninghub.com
Exception Handling
What is Exception?
• An Exception is a runtime error
• To represent all types of exceptions there Is an Exception
class in Java
• A variety of subclasses allows handling different kinds of
errors & abnormal events
• Basic concept:
• Whenever an abnormal event occurs. Java throws an Exception
• It means Java creates an object of subclass of the Exception class
• Whenever an Exception could possibly be thrown, we must provide
a mechanism for catching it in our code
www.prolearninghub.com
Kind of Exception
There are three kind of exceptions:
• Checked exceptions
• Errors
• Runtime exceptions
www.prolearninghub.com
Kind of Exception
Checked Exception:
These are exceptional conditions that a well written
program should anticipate and recover from. For example
an application prompts a user from an input file name,
and then open the file by passing the name to the
constructor. IOException, SQLException are checked
exceptions.
www.prolearninghub.com
Kind of Exception
Errors:
These are exceptional conditions that are external to
the application, and that the application usually cannot
anticipate or recover from. For example an application
is successfully opens a file for input, but is unable to
read the file because of the hardware of system
malefaction .
Examples:
OutOfMemoryError, VirtualMachineError,
www.prolearninghub.com
AssertionError are errors.
Kind of Exception
Runtime exceptions:
These are exceptional conditions that are internal to the
application, and that are application could not recover or
anticipate from.
Examples:
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
www.prolearninghub.com
Exception Handling
Catching Exception
• A try statement executes a block and oversees the
execution of enclosed statements for exceptions
• A try also defines the scope for exception handlers
(defined in catch clause)
• A try block must be accompanied by at least one
catch block or one finally block
• Any method declared as being able to throw an
Exception, can have a try / catch block to handle the
exception
www.prolearninghub.com
Exception Handling
Catching Exception
Java try block is used to enclose the code that might
throw an exception. It must be used within the
method.
Java try block must be followed by either catch or
finally block.
www.prolearninghub.com
Exception Handling
Catching Exception
Syntax of java try-catch
try{
//code that may throw exception
}catch(Exception_class_Name ref){}
Syntax of try-finally block
try{
//code that may throw exception
}finally{}
www.prolearninghub.com
Exception Handling
Exception Example
public class ExceptionDemo1 {
public static void main(String [ ] args) {
int [ ] x = {1,2,3};
try {
System.out.println(“x[0] = * + x[0]);
System.out.println("x[5] = * + x[5]);
}
catch(ArraylndexOutOfBoundsException ae) {
System.out.println("Index Does Not Exist");
}
}
}
www.prolearninghub.com
Exception Handling
Exception Example
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
www.prolearninghub.com
Object
Exception
Handling
Throwable
Error
...
Exception
...
Exception Hierarchy
RuntimeException
...
www.prolearninghub.com
Exception Handling
Categories of Exception
 Java exceptions fall in two categories:
1. Unchecked
-
Not checked by the compiler at compile time
Does not force the client program / method to declare each exception thrown by a
method, or even handle it
All exceptions are derived from RuntimeException class
2. Checked
- Checked by the compiler to see if these exceptions are properly caught or
specified, & if not. the code fails to compile
- Forces client program to deal with the scenario in which an exception may be
thrown
- All exceptions which are not derived from RuntimeException class
www.prolearninghub.com
Exception Handling
Multiple Catch Blocks
•
A method can throw more than one possible Exceptions, or the try block
could call two different methods that throw two different Exceptions
try {
String text = "text";
System.out.println(text.charAt(10));
int n = Integer.parseInt("abc");
} catch(IndexOutOfBoundsException e) {
System.err.printIn(“Index out of bounds");
e.printStackTrace();
} catch(NumberFormatException e) {
System.err.printIn("bad number");
e.printStackTrace();
}
www.prolearninghub.com
Exception Handling
Multiple Catch Blocks
• Since all Exceptions are subclasses of the Exception class,
we can generalize catch blocks to accept multiple different
types of Exceptions by using a super class
try {
String text = "text";
System.out.println(text.charAt(10));
int n = Integer.parseInt("abc");
} catch(Exception e) {
System.err.printIn(“Something bad happened");
e.printStackTrace();
}
www.prolearninghub.com
Exception Handling
The finally Block
•
•
•
Sometimes, while in a try / catch block, an Exception could be thrown
before some important code at the end of the try block
The finally block can be used to run this code
Code in finally always executes (even in case of unhandled exceptions)
try {
String text = "text";
System.out.println(text.charAt(10));
} catch(lndexOutOfBoundsException e) {
System.err.println("Index out of bounds");
e.printStackTrace();
} finally {
System.out.println("This is going to Excecute always");
}
www.prolearninghub.com
Exception Handling
Exception Propagation
• Exceptions are always propagated from the called method to
the caller method, if thrown from the called method
• If an Exception is thrown from the main() method, it will be
propagated to the Java Runtime
• In exception propagation, all statement executions are ignored
until finding the exception handler
www.prolearninghub.com
Exception Handling
Arithmetic
Exception
Occurred
public class Propagate {
void calculate() {
int n = 25, i = 0;
i = n/i;
}
public static void main(String[] args) {
Propagate p = new Propagate();
p.calculate();
}
}
Exception
propagated
from
calculate ()
to main ()
method
Exception in thread “main" java.lang.ArithmeticException: / by zero
at Propagate.calculate(Propagate.java:4)
at Propagate.main(Propagate.java:8)
Exception propagated from main() function to Java
www.prolearninghub.com
Summary
Summary
In this session, we have covered:
 Exception Handling
• Introduction
• Checked & Unchecked Exceptions
• Using try, catch, finally
• Exception Propagation
www.prolearninghub.com
Sample Exercise #1
What type of exception is divide by zero is ?
This is an athematic exception .
www.prolearninghub.com