ExceptionHandling PDF
ExceptionHandling PDF
Eg:
Suppose there is an Exception in main thread....
We have exceptioj as follows :
Exception in thread main:java.lang.Arithemetic Exception:division
by Zero
At somemethod();
“““““““ ““
“ “ “” ”” ” ””
“ ” “” “ “” “” “
System.out.println("Haiiiiii");
Thread.sleep(1000); //interrupted exception
}
}
All the sub-classes of exception class except “RUNTIME
EXCEPTION” is checked exception......including the ERROR
class...and all of its sub classes.
If the parent class is checked and its child class is also checked
We say it is fully checked
Eg:
IOexception(checked)(parent)
.FilenotFoundEXception(child)(checked)
PARTIALLY CHECKED exceptions are those in which parent
class is checked but its child classes maybe unchecked...its is said
to be partial....
Eg:
Throwable class
Exception class....
EXAMPLE PROGRAM
// try {
// System.out.println(10/0);
// } catch (Exception e) {
//
// System.out.println("cannot divide a
number by zero");
// }
//(compile time error finally {
System.out.println("hello beautiful");
}
}
}
CASES FOR CONTROL FLOW
VARIOUS POSSIBLE COMBINATIONS OF try
catch and finally
Throw keyword
Output:
Output:
Case2:
If any code written after throw will become
unreachable.....even return return statement
cannot be written.
}
}
CASE:3
public class ExceptionFinally {
public static void main(String[] args) {
throw new ExceptionFinally();//complie
time error
}
}
As we can see ExceptionFinally is not a
subclass of Throwable class hence we get
compile time error.
To over come this just extend the class by
Any of the subclasses of Throwable......ie
Eg:
public class ExceptionFinally extends
RuntimeException {
public static void main(String[] args) {
}
}
Now here there is a catch “only unchecked
exceptions it can extend......(not that it
cannot extend checked exceptions....but
we’ll have to handle it as complier will know
there is a chance of exception).
Eg:
If we use Throwable class or exception class
we have:
public class ExceptionFinally extends
Exception {
public static void main(String[] args) {
ExceptionInInitializer Error:
ILLegalArgumenyException(unchecked)
Number format exception:
(unchecked)
We get this when we perform debugging when we use assertion statement ….and this statemnt fails.
WITH TRY WITH reources ...we do not have to write a finally block to close resources will automayically be closed...
Important points wrt try with resources
• We can juse any number of resources in try block but they msut
be separated by comma
•
• Whatever resources used with this trty should be autocloaseable...ie any resource or corresponding class
implements autocloseable interface is known a autocloasebale
•
• From 1.7 version only try with resource xan be written
•
• Notes:
Complusory all resources should be include within try.(in 1.7 or 1.8)versions
Note:
there should not be any relation between the exceptins in catch block
Re throwing exception: