Yugandhar Java Unit-3 Final Version
Yugandhar Java Unit-3 Final Version
Yugandhar Java Unit-3 Final Version
O
UNIT
-3 O
PROGRAMMING
A860
1
ORIENTED
PRESENTED BY
OBJECT M.YGANDHAR
Department of IT
Vardhaman College of Engineering
01 Exception-Handling 02 Exception Types,
TOPIC Fundamentals TOPIC Using try catch
07 08
Synchronizing threads Interthread Communication.
TOPIC TOPIC
Exception-Handling Fundamentals
An exception is an abnormal condition that arises in a code at run time. In other words, an exception is a
runtime error.
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, below given are some scenarios where exception
occurs.
i. Division by zero
ii. Array out of bound access exception
iii. A user has entered invalid data.
iv. A file that needs to be opened cannot be found.
v. A network connection has been lost in the middle of communications
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
Exception-Handling
“Exception handling is the mechanism to handle run time errors, so that the normal flow of application can
be maintained.”
Exception Handling is managed by using 5 Keywords.
1. try
2. catch
3. throw
4. throws
5. finally
Types of Java Exceptions
There are mainly three types of exceptions:
i. User Defined Exceptions
ii. Built in Exceptions
i. Checked Exception
ii. Unchecked Exception
Types of Exceptions
i.Checked exceptions:
A checked exception is an exception that occurs at the compile time, these are also called as compile
time exceptions.
These exceptions cannot simply be ignored at the time of compilation, the Programmer should take care
of (handle) these exceptions.
For example, if you use FileReader class in your program to read data from a file, if the file specified in
its constructor doesn't exist, then an FileNotFoundException occurs, and compiler prompts the
programmer to handle the exception.
i.Checked exceptions
1. ClassNotFoundException: This exception is thrown when the JVM tries to load a class, which is not
present in the classpath.
Class.forName("oracle.jdbc.driver.OracleDriver");
2. FileNotFoundException: This exception is thrown when the program tries to access a file that does not
exist or does not open. This error occurs mainly in file handling programs.
3.IOException: This exception is thrown when the input-output operation in a program fails or is interrupted
during the program’s execution.
4.InterruptedException: This exception occurs whenever a thread is processing, sleeping or waiting in a
multithreading program and it is interrupted.
Thread t = new Thread();
t.sleep(10000);
Types of Exceptions
import java.io.File;
import java.io.FileReader;
public class FilenotFound_Demo
{
public static void main(String args[])
{
File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile the above program you will get exceptions as shown below.
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared
to be thrown
FileReader fr = new FileReader(file);
^
1 error
Some of the examples of checked exceptions
Types of Exceptions
ii.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.
For example, if you have declared an array of size 5 in your program, and trying to call the 6th element of
the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a
try block.
Immediately following the try block, include a catch clause that specifies the exception type that you
wish to catch.
ii.Unchecked exceptions
1.ArithmeticException: This exception occurs when a program encounters an error in arithmetic operations
such as divide by zero. class Test
{ OUTPUT
public static void main(String[] args) D:\>java Test
{ Exception in thread "main"
System.out.println(120/0); java.lang.ArithmeticException: / by
} zero
}
4.NumberFormatException: This exception is thrown when a method could not convert a string
class Test
into a numeric format.
{
public static void main(String[] args)
{
String a = "abc";
int num=Integer.parseInt(a);
}
}
ii.Unchecked exceptions
5. StringIndexOutOfBoundsException: This exception is thrown by the string class, and it indicates that the
index is beyond the size of the string object or is negative.
class Test
{
public static void main(String[] args)
{
String a = "JAVA";
char c = a.charAt(6); // accessing 6 index element
System.out.println(c);
}
}
ii.Unchecked exceptions
Printing Exception information
The following are the methods to fetch exception information:
i. obj.stackTrace() ---------------> Name of the Exception: Description -> StackTrace
ii. obj.toString() -----------------> Name of the Exception: Description
iii. obj.getMessage() -----------> Description
class Test class Test class Test
{ { {
public static void main(String[] args) public static void main(String[] args) public static void main(String[] args)
{ { {
int a[] = {11,22}; int a[] = {11,22}; int a[] = {11,22};
try try try
{ { {
System.out.println(a[9]); System.out.println(a[9]); System.out.println(a[9]);
} } }
catch (Exception e) catch (Exception e) catch (Exception e)
{ { {
e.printStackTrace();
System.out.println(e.toString()); System.out.println(e.getMessage());
}
} }
}
} }
}
} }
java.lang.ArrayIndexOutOfBoundsExceptio
n: Index 9 out of bounds for length 2 java.lang.ArrayIndexOutOfBoundsExceptio Index 9 out of bounds for length 2
at Test.main(Test.java:8) n: Index 9 out of bounds for length 2
USING TRY AND CATCH
This is the general form of an exception-handling block:
try
{
---------------// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
---------------// exception handler for ExceptionType1
}
USING TRY AND CATCH
ExceptionType is the type of exception that has occurred.
Program Statements that we monitor for exceptions are contained in try block.
If an exception occurs in try block, it is thrown.
The code can catch this exception using catch block and handle the exception in a rational manner.
System generated exceptions are automatically thrown by the Java runtime.
Catch block is used to handle the exception, called Exception Handler.
Must be used after try block only. We can use multiple catch blocks with a single try block.
The throw keyword is used to manually throw an exception
Any code that absolutely must be executed after a try block completes is put in finally block.
class Exc2
{
public static void main(String args[])
{
int d, a;
try
{
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
} Output
System.out.println("After catch statement."); Division by zero.
After catch statement
}
}
MULTIPLE CATCH CLAUSES
In some cases, more than one exception could be raised by a single piece of code.
To handle this type of situation, you can specify two or more catch clauses, each catching a different
type of exception.
When an exception is thrown, each catch statement is inspected in order, and the first one whose type
matches that of the exception is executed.
After one catch statement executes, the others are bypassed, and execution continues after the
try/catch block. try
{
Syntax of Multiple catch statements:
// block of code to monitor for errors
}
catch (ExceptionType1 exOb)
{
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb)
{
// exception handler for ExceptionType2
}
MULTIPLE CATCH CLAUSES
// Demonstrate multiple catch statements.
class MultiCatch {
public static void main(String args[])
{
try
{
int a = 10;
System.out.println("a = " + a); Output
int b = 42 / a; a = 10
int c[] = { 1 }; Array index oob:
c[42] = 99; java.lang.ArrayIndexOutOfBoundsException:
} Index 42 out of bounds for length 1
catch(ArithmeticException e) After try and catch blocks.
{
System.out.println("Divide by 0: " + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index oob: " + e);
}
System.out.println("After try and catch blocks.");
}
}
NESTED TRY STATEMENTS
The try statement can be nested.
That is, a try statement can be inside the block of another try.
If an inner try statement does not have a catch handler for a particular exception, the stack is unwound
and the next try statement’s catch handlers are inspected for a match.
This continues until one of the catch statements succeeds, or until the entire nested try statements are
exhausted.
If no catch statement matches, then the Java run-time system will handle the exception. Here is an
example that uses nested try statements:
// An example of nested try statements.
class NestTry
{
public static void main(String args[])
{
try
{
int a[] = {1,2,3,0,4};
try
{
int b=a[2]/a[3];
}
OUTPUT:
catch(ArithmeticException e)
C:\>java NestTry
{ java.lang.ArithmeticException: / by zero
System.out.println( e); java.lang.ArrayIndexOutOfBoundsException
}
a[20]=44;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
}}
THROW
So far, you have only been catching exceptions that are thrown by the Java run-time system.
However, it is possible for your program to throw an exception explicitly, using the throw statement
throw keyword is used to explicitly throw an exception from a method or constructor.
We can throw either checked or unchecked exceptions in java by throw keyword.
The "throw" key-word is mainly used to throw a custom exception.
When a throw statement is encountered, program execution is halted, and the nearest catch statement is
searched for a matching kind of exception.
The general form of throw is shown here: Syntax
throw ThrowableInstance;
Example-1 Example-2
throw new ArithmeticException( ); throw new ArithmeticException(“Something went wrong!”);
// Demonstrate throw.
class Test
{
static void avg()
{
try
{
throw new ArithmeticException("demo");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught“+e);
}
}
Syntax
<return_type> <method_name> ( ) throws <excpetion_name1>, <exception_name2>
{
// body of method
}
Example
void Display( ) throws ArithmeticException, NullPointerException
{
//code
}
class Test
{
static void check() throws ArithmeticException
{
System.out.println("Inside check function");
throw new ArithmeticException("demo");
}
Syntax
class <name of the class> extends Exception
{
public String toString()
{
Statements;
}
}
Creating own exception
Example
class MyException extends Exception
{ class Test
String str1; {
MyException(String s) public static void main(String args[])
{ {
str1=s; try
} {
public String toString() System.out.println("Starting of try block");
{ throw new MyException("This is My error Message");
return ("MyException Occurred: "+str1) ; }
} catch(MyException exp)
} {
System.out.println("Catch Block") ;
System.out.println(exp) ;
}
OUTPUT
}
Starting of try block
Catch Block }
MyException Occurred: This is My error Message
Example
class InsufficientFundsException extends Exception else
{ throw new InsufficientFundsException("No Balance in your account");
InsufficientFundsException(String s) }
{ catch (InsufficientFundsException e)
super(s); {
} System.out.println(e.getMessage());
} }
class Test finally
{ {
public static void main(String[] args) System.out.println("Updated Balance:"+balance);
{ System.out.println("Pls take your card");
java.util.Scanner obj = new }
java.util.Scanner(System.in); }
double balance = 10000.00; }
double amt = obj.nextDouble();
try
{
if(amt<=balance)
{
System.out.println("pls take the cash");
OUTPUT
balance = balance - amt;
}
Multi Threading
Multi Threading is a specialized form of multi tasking.
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
Process-based Multitasking (Multiprocessing)
Thread-based Multitasking (Multithreading)
Executing several tasks simultaneously where each task is a separate independent process such type of
multitasking is called process based multitasking.
Executing several tasks simultaneously where each task is a separate independent part of the same
program, is called Thread based multitasking. And each independent part is called a "Thread"
Multithreading refers to a process of executing two or more threads simultaneously for maximum
utilization of the CPU.
Multithreading is a feature in Java that concurrently executes two or more parts of the program.
Multi Threading
A thread in Java is a lightweight process requiring fewer resources.
Each thread runs parallel to each other.
Java Provides built in support for multi threaded programming.
Threads share common memory area.
A main program is also single thread.
Advantages of MultiThreading
Allows to write very efficient program that makes maximum use of CPU.
Throughput – Amount of work done in unit time increase.
It is used to save time as multiple operations are performed concurrently.
The threads are independent, so it does not block the user to perform multiple operations at the same
time.
Since threads are independent, other threads don’t get affected even if an exception occurs in a single
thread.
Thread Life Cycle
The life cycle of a thread in Java is controlled by JVM.
During the execution of thread, it is in any of the following five states.
Hence Java thread life cycle is defined in five states.
Thread Life Cycle
i. New: The thread is in new state when the instance of thread class is created but before the calling of start()
method.
ii. Runnable: The thread is in runnable state after the invocation start() method, but the thread scheduler has
not selected it to be the running thread. Any number of threads exists in this state.
iii. Running: The thread is in running state when the thread scheduler selects a thread for execution.
iv. Waiting/blocked/sleeping: this is the state when the thread is still alive but is not eligible currently to run.
v. (Blocked) Terminated: A thread is in terminated or dead state when its run() method exits.
We can define a Thread in the following 2 ways.
7.public static Thread currentThread(): returns the reference of currently executing thread.
8. Public static void sleep(long miliseconds): Causes the currently executing thread to suspend (temporarily
10.public boolean isAlive(): to check the thread is still running. Returns true if the thread is still running.
11.public void yield(): causes the currently executing thread object to temporarily pause and allow other
threads to execute.
Producer Thread- Produce items to Buffer (Add Items) Consumer Thread- Consume items from Buffer
(Removes Items).
The two conditions for Producer – Consumer Problem is :
1. Producer cannot add an item into a buffer if it is full
2. Consumer cannot consume an item if it is empty.
If no communication, these two conditions are not satisfied then the CPU is always in polling (loop).
To Save CPU time in Java Interthread communication is used.
Producer Consumer Problem for Interthread Communication
//Producer-Consumer problem ---> Inter Thread Communication.
class Buffer
{
int item; synchronized int consume()
boolean produced = false; {
synchronized void produce(int x) if(!produced)
{ {
if(produced) try{
{ wait();
try{ }
wait(); catch(InterruptedException ie)
} {
catch(InterruptedException ie) System.out.println("Exception Caught " +ie);
{ }
System.out.println("Exception }
Caught"); System.out.println("Consumer - Consumed " +item);
} produced = false;
} notify();
item =x; return item;
System.out.println("Producer - Produced-->" +item); }
produced =true; }
notify();
}
Producer Consumer Problem for Interthread Communication
class Consumer extends Thread
{
class Producer extends Thread Buffer b;
{ Consumer(Buffer b)
Buffer b; {
Producer( Buffer b) this.b = b;
start();
{
}
this.b = b; public void run()
start(); {
} b.consume();
public void run() b.consume();
{ b.consume();
b.produce(10); b.consume();
b.produce(20); }
}
b.produce(30);
public class PCDemo
b.produce(40); {
b.produce(50); public static void main(String args[])
} {
} Buffer b = new Buffer(); //Synchronized Object
Producer p = new Producer(b);
Consumer c = new Consumer(b);
}
}
N
H A ‘Q’
T