EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
Unit 4 exceptions and threads
1.
2. An exception (or exceptional event) is a problem that
arises during the execution of a program.
When an Exception occurs the normal flow of the
program is disrupted and the program/Application
terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
An exception can occur for many different reasons.
A user has entered an 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.
3. Checked exceptions − A checked exception is an exception
that is checked (notified) by the compiler at compilation-
time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer
should take care of () these exceptions. Eg:
FileNotFoundException
Unchecked exceptions − An unchecked exception is an
exception that occurs at the time of execution. These are also
called as Runtime Exceptions. These include programming
bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Eg: ArrayIndexOutOfBoundsExceptionexception
Errors − These are not exceptions at all, but problems that
arise beyond the control of the user or the programmer.
Errors are typically ignored in your code because you 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.
4.
5. Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
A try/catch block is placed around the code that might
generate an exception. Code within a try/catch block is
referred to as protected code.
Syntax
try{
//code that may throw an exception
}catch(Exception_class_Name ref)
{
}
The code which is prone to exceptions is placed in the
try block.
When an exception occurs, that exception occurred is
handled by catch block associated with it.
Every try block should be immediately followed either
by a catch block or finally block.
6. A catch statement involves declaring the type
of exception you are trying to catch.
If an exception occurs in protected code, the
catch block (or blocks) that follows the try is
checked.
If the type of exception that occurred is listed in
a catch block, the exception is passed to the
catch block much as an argument is passed into
a method parameter.
7. import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" +
a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
8. try The "try" keyword is used to specify a block where
exception code should be placed. The try block must be
followed by either catch or finally. It means, we can't use
try block alone.
catch The "catch" block is used to handle the exception. It must
be preceded by try block ,i.e catch block alone cannot be
used. It can be followed by finally block later.
finally The "finally" block is used to execute the important code
of the program. It is executed whether an exception is
handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It
doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.
9. public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
11. A try block can be followed by one or more
catch blocks. Each catch block must contain a
different exception handler.
At a time only one exception occurs and at a
time only one catch block is executed.
All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before catch
for Exception.
12. public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
13. public class MultipleCatchBlock2
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
o/p: Arithmetic Exception occurs
14. public class MultipleCatchBlock3{
public static void main(String[] args) {
try{
Int a=25/0;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
Arithmetic exception is generate d, but the corresponding exception type
is not provided. In such case, the catch block containing the parent
exception class Exception will invoked.
15. In a method, there can be more than one statements that might
throw exception, So put all these statements within its own try
block and provide separate exception handler within own catch
block for each of them.
If an exception occurs within the try block, that exception is
handled by the exception handler associated with it. To associate
exception handler, we must put catch block after it.
There can be more than one exception handlers. Each catch block
is a exception handler that handles the exception of the type
indicated by its argument. The argument, ExceptionType declares
the type of the exception that it can handle and must be the name
of the class that inherits from Throwable class.
For each try block there can be zero or more catch blocks, but only
one finally block.
The finally block is optional.It always gets executed whether an
exception occurred in try block or not .
If exception occurs, then it will be executed after try and catch
blocks. And if exception does not occur then it will be executed
after the try block.
The finally block in java is used to put important codes such as
clean up code e.g. closing the file or closing the connection.
16. The try block within a try block is known as nested try block in java.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
17. class NestedException1{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
18. class NestedException2 {
public static void main(String args[])
{
try {
try {
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
// handles ArithmeticException if any
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" try-block2");
}
}
// handles ArrayIndexOutOfBoundsException if any
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" main try-block");
}
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
19. Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
Java finally block is always executed whether
exception is handled or not.
Java finally block follows try or catch block.
20.
21. Example where exception doesn't occur.
class FinallyBlockTest 1{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
22. Exception occurs and not handled.
class FinallyBlockTest2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
23. Exception occurs and handled.
public class FinallyBlockTest3{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
24. Definition: Throw is a keyword which is used to throw an
exception explicitly in the program inside a function or
inside a block of code.
Internal implementation : Internally throw is implemented
as it is allowed to throw only single exception at a time i.e
we cannot throw multiple exception with throw keyword.
Type of exception: With throw keyword we can propagate
only unchecked exception i.e checked exception cannot be
propagated using throw.
Syntax: Syntax wise throw keyword is followed by the
instance variable.
Declaration: throw keyword is used within the method. void
m(){
throw new ArithmeticException("sorry");
}
25. public class ThrowTest{
public void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible
for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
ThrowTest obj = new ThrowTest();
obj.checkAge(13);
System.out.println("End Of Program");
}
}
26. Definition: Throws is a keyword used in the method
signature used to declare an exception which might get
thrown by the function while executing the code.
Internal implementation: can declare multiple
exceptions with throws keyword that could get thrown
by the function where throws keyword is used.
Type of exception: with throws keyword both checked
and unchecked exceptions can be declared keyword
followed by specific exception class name.
Syntax : throws keyword is followed by exception
class names.
Declaration : throws keyword is used with the method
signature.
void m()throws ArithmeticException{
//method code
}
27. public class ThrowsTest{
public int division(int a, int b) throws
ArithmeticException,IOException{
int t = a/b;
return t;
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide number by
zero");
}
}
}
28. throw throws
Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to
declare an exception that might
occur.
Checked exception cannot be
propagated using throw only. It is
useful specially with custom
exceptions.
Checked exception can be
propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method or
block.
Throws is used with the method
signature.
Exception object is manually
thrown by programmer, it is handled
by JVM
Exception specified using throws is
taken care by the caller method.
You cannot throw multiple
exceptions.
You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.
29. Java custom exceptions or user defined
exceptions are used to customize the exception
according to user need.
User can create their own exception class and
throws that exception using ‘throw’ keyword.
custom exceptions are created by extending the
class Exception.
30. class InvalidAgeException extends RuntimeException{
InvalidAgeException(String s){
super(s);
}
}
class CustomExceptionTest1{
static void validate(int age) {
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
31. Built-in exceptions are the exceptions which are available in Java
libraries.
Following are examples of unchecked exceptions
Sr.N
o.
Exception & Description
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 ArrayStoreException
Assignment to an array element of an incompatible
type.
32. 4 NegativeArraySizeException
Array created with a negative size.
5 NullPointerException
Invalid use of a null reference.
6 NumberFormatException
Invalid conversion of a string to a numeric format.
7 SecurityException
Attempt to violate security.
8 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
9 UnsupportedOperationException
An unsupported operation was encountered.
33. Sr.No. Exception & Description
1 ClassNotFoundException
Class not found.
2 IllegalAccessException
Access to a class is denied.
3 InstantiationException
Attempt to create an object of an abstract class or interface.
4 InterruptedException
One thread has been interrupted by another thread.
5 NoSuchFieldException
A requested field does not exist.
6 NoSuchMethodException
A requested method does not exist.
34. A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the
same time making optimal use of the available resources.
Multi threading subdivides specific operations within a single
application into individual threads.
Each of the threads can run in parallel.
The OS divides processing time not only among different
applications, but also among each thread within an application.
Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.
Multithreading in Java is a process of executing multiple threads
simultaneously.
A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
However, we use multithreading than multiprocessing because
threads use a shared memory area. They don't allocate separate
memory area so saves memory.
35. Thread is smallest unit of processing. It is a separate
path of execution.
Threads are independent. If there occurs exception in
one thread, it doesn't affect other threads. It uses a
shared memory area.
36. A thread goes through various stages in its life cycle.
For example, a thread is born, started, runs, and then
dies. The following diagram shows the complete life
cycle of a thread.
37. Every Java thread has a priority that helps the
operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between
MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default,
every thread is given priority NORM_PRIORITY
(a constant of 5).
Threads with higher priority are more important to
a program and should be allocated processor time
before lower-priority threads. However, thread
priorities cannot guarantee the order in which
threads execute and are very much platform
dependent.
38. Thread creation in Java;
Thread implementation in java can be achieved in two ways:
Extending the java.lang.Thread class
Implementing the java.lang.Runnable Interface
Note: The Thread and Runnable are available in the
java.lang.* package
1) By extending thread class
The class should extend Java Thread class.
The class should override the run() method.
The functionality that is expected by the Thread to be
executed is written in the run() method.
void start(): Creates a new thread and makes it runnable.
void run(): The new thread begins its life inside this method.
39. public class ThreadTest1 extends Thread {
public void run(){
System.out.println("thread is running...");
}
public static void main(String[] args) {
ThreadTest1 obj = new ThreadTest1();
obj.start();
}
40. By Implementing Runnable interface
The class should implement the Runnable interface
The class should implement the run() method in
the Runnable interface
The functionality that is expected by the Thread to
be executed is put in the run() method
public class ThreadTest2 implements Runnable {
public void run(){
System.out.println("thread is running..");
}
public static void main(String[] args) {
Thread t = new Thread(new ThreadTest2());
t.start();
}
41. Ending Thread:
A Thread ends due to the following reasons:
The thread ends when it comes when the run()
method finishes its execution.
When the thread throws an Exception or Error
that is not being caught in the program.
Java program completes or ends.
Another thread calls stop() methods.