Unit 2 Notes
Unit 2 Notes
Unit 2
Lecture 13
Lecture 13
• The Idea behind Exception
• Exceptions & Errors
• Types of Exception, Checked and Un-Checked
Exceptions
Exception Handling
Exception Handling in Java is one of the
effective means to handle runtime errors so
that the regular flow of the application can be
preserved.
Java Exception Handling is a mechanism to
handle runtime errors such as
ClassNotFoundException, IOException,
SQLException, RemoteException, etc.
Control Flow in Exceptions
The core advantage of exception handling is
to maintain the normal flow of the application.
An exception normally disrupts the normal
flow of the application; that is why we need to
handle exceptions.
Let's consider a scenario
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in a Java
program and an exception occurs at statement 5;
the rest of the code will not be executed, i.e.,
statements 6 to 10 will not be executed. However,
when we perform exception handling, the rest of
the statements will be executed. That is why we
use exception handling in Java.
The Idea behind Exception
• Exception is an unwanted or unexpected
event, which occurs during the execution of
a program, i.e. at run time, that disrupts the
normal flow of the program’s instructions.
• Exceptions can be caught and handled by
the program.
• When an exception occurs within a method,
it creates an object.
• This object is called the exception object.
• It contains information about the exception,
such as the name and description of the
exception and the state of the program
when the exception occurred.
Major reasons why an exception Occurs
1. Built-in Exceptions
➢ Checked Exception
➢ Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions
Built-in exceptions are the exceptions that are
available in Java libraries. These exceptions are
suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are
called compile-time exceptions because these
exceptions are checked at compile-time by the
compiler.
Unchecked Exceptions:
The unchecked exceptions are just opposite to the
checked exceptions.
The compiler will not check these exceptions at
compile time.
In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it,
the program would not give a compilation error.
2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases,
users can also create exceptions, which are called
‘user-defined Exceptions’.
The advantages of Exception Handling in Java are
as follows:
• Provision to Complete Program Execution
• Easy Identification of Program Code and Error-
Handling Code
• Propagation of Errors
• Meaningful Error Reporting
• Identifying Error Types
Object Oriented Programming with Java
(Subject Code: BCS-403)
Unit 2
Lecture 14
Lecture 14
• Control Flow in Exceptions
• JVM Reaction to Exceptions
• Use of try, catch and finally
Flow control in try catch finally in Java
1.Control flow in try-catch clause OR try-catch-
finally clause
1.Case 1: Exception occurs in try block and handled in
catch block
2.Case 2: Exception occurs in try-block is not handled
in catch block
3.Case 3: Exception doesn’t occur in try-block
2.try-finally clause
1.Case 1: Exception occurs in try block
2.Case 2: Exception doesn’t occur in try-block
Exception occurs in try block and handled
in catch block
If a statement in try block raised an
exception, then the rest of the try block
doesn’t execute and control passes to
the corresponding catch block.
After executing the catch block, the control
will be transferred to finally block(if present)
and then the rest program will be executed.
Exception occurred in try-block is not
handled in catch block
In this case, the default handling mechanism
is followed.
If finally block is present, it will be executed
followed by the default handling
mechanism.
Exception doesn’t occur in try-block:
In this case catch block never runs as they
are only meant to be run when an exception
occurs. finally block(if present) will be
executed followed by rest of the program.
class A
{
public static void main (String[] args)
{
try
{
String str = "123";
int num = Integer.parseInt(str);
System.out.println("try block fully executed");
}
catch(NumberFormatException ex)
{
System.out.println("catch block executed...");
}
finally
{
System.out.println("finally block executed");
}
System.out.println("Outside try-catch-finally clause");
}
}
Control flow in try-finally
In this case, no matter whether an exception occurs
in try-block or not finally will always be executed.
But control flow will depend on whether an
exception has occurred in the try block or not.
Unit 2
Lecture 15
Lecture 15
• Throw and throws in Exception Handling
throw keyword
• The Java throw keyword is used to throw an
exception explicitly.
• We specify the exception object which is to be
thrown. The Exception has some message with
it that provides the error description. These
exceptions may be related to user inputs,
server, etc.
• We can throw either checked or unchecked
exceptions in Java by throw keyword. It is
mainly used to throw a custom exception.
• We can also define our own set of
conditions and throw an exception explicitly
using throw keyword.
• For example, we can throw
ArithmeticException if we divide a number
by another number.
• Here, we just need to set the condition and
throw exception using throw keyword.
syntax of the Java throw keyword
public class Main {
public static void main(String[] args) {
int dividend = 10;
int divisor = 0;
if (divisor == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
}
else {
System.out.println("Person is eligible to vote!!");
}
}
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Note: If we throw unchecked exception from a
method, it is must to handle the exception or
declare in throws clause.
Java throws keyword
• The Java throws keyword is used to declare an
exception. It gives an information to the
programmer that there may occur an exception
so it is better for the programmer to provide the
exception handling code so that normal flow can
be maintained.
• Exception Handling is mainly used to handle the
checked exceptions. If there occurs any
unchecked exception such as
NullPointerException, it is programmers fault that
he is not performing check up before the code
being used.
• In a program, if there is a chance of raising an
exception then the compiler always warns us
about it and compulsorily we should handle that
checked exception, Otherwise, we will get
compile time error saying unreported exception
xyz must be caught or declared to be thrown.
• To prevent this compile time error we can handle
the exception in two ways:
➢ By using try catch
➢ By using the throws keyword
Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}
Rule: If you are calling a method that declares an exception,
you must either caught or declare the exception.
There are two cases:
• Case1:You caught the exception i.e. handle the exception
using try/catch.
• Case2:You declare the exception i.e. specifying throws
with the method.
// Java program to illustrate error in case
// of unhandled exception
class MyMain {
public static void main(String[] args)
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Output
error: unreported exception InterruptedException; must be caught or declared to be
thrown
// Java program to illustrate throws
class {
public static void main(String[] args)
throws InterruptedException
{
Thread.sleep(10000);
System.out.println("Hello Geeks");
}
}
Important Points to Remember about throws
Keyword
• throws keyword is required only for checked
exceptions and usage of the throws keyword for
unchecked exceptions is meaningless.
• throws keyword is required only to convince
the compiler and usage of the throws keyword
does not prevent abnormal termination of the
program.
• With the help of the throws keyword, we can
provide information to the caller of the method
about the exception.
Difference Between throw and throws
throw throws
The throw keyword is used inside a The throws keyword is used in the
function. It is used when it is function signature. It is used when
required to throw an Exception the function has some statements
logically. that can lead to exceptions.
Unit 2
Lecture 16
Lecture 16
• In-built and User Defined Exceptions
Java defines several types of exceptions that relate
to its various class libraries. Java also allows users
to define their own exceptions.
Built-in Exceptions
Built-in exceptions are the exceptions that are
available in Java libraries. These exceptions are
suitable to explain certain error situations.
• ArithmeticException: It is thrown when an exceptional
condition has occurred in an arithmetic operation.
• ArrayIndexOutOfBoundsException: It is thrown to
indicate that an array has been accessed with an illegal
index. The index is either negative or greater than or
equal to the size of the array.
• ClassNotFoundException: This Exception is raised
when we try to access a class whose definition is not
found
• FileNotFoundException: This Exception is raised when
a file is not accessible or does not open.
• IOException: It is thrown when an input-output
operation failed or interrupted
• InterruptedException: It is thrown when a thread is
waiting, sleeping, or doing some processing, and it is
interrupted.
• NoSuchFieldException: It is thrown when a class does
not contain the field (or variable) specified
• NoSuchMethodException: It is thrown when accessing
a method that is not found.
• NullPointerException: This exception is raised when
referring to the members of a null object. Null
represents nothing
• NumberFormatException: This exception is raised
when a method could not convert a string into a
numeric format.
• RuntimeException: This represents an exception that
occurs during runtime.
• StringIndexOutOfBoundsException: It is thrown by
String class methods to indicate that an index is either
negative or greater than the size of the string
• IllegalArgumentException : This exception will throw
the error or error statement when the method
receives an argument which is not accurately fit to the
given relation or condition. It comes under the
unchecked exception.
// Java program to demonstrate ArithmeticException
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
//Java program to demonstrate NullPointerException
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException..");
}
}
}
// Java program to demonstrate NumberFormatException
class NumberFormat_Demo
{
public static void main(String args[])
{
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;
System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
User-Defined Exceptions
• the built-in exceptions in Java are not able to
describe a certain situation.
• In such cases, the user can also create
exceptions which are called ‘user-defined
Exceptions’.
• The user should create an exception class as a
subclass of the Exception class.
• Since all the exceptions are subclasses of the
Exception class, the user should also make his
class a subclass of it.
Create user-defined Exception
The following steps are followed for the creation of a
user-defined Exception.
class MyException extends Exception
We can write a default constructor in his own
exception class.
MyException(){}
We can also create a parameterized constructor
with a string as a parameter.
We can use this to store exception details. We can
call the superclass(Exception) constructor from this
and send the string there.
MyException(String str)
{
super(str);
}
To raise an exception of a user-defined type, we
need to create an object to his exception class and
throw it using the throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
Object Oriented Programming with Java
(Subject Code: BCS-403)
Unit 2
Lecture 17
Lecture 17
• Byte Streams and Character Streams
• Reading and Writing File in Java
Byte Streams and Character Streams
In Java the streams are used for input and
output operations by allowing data to be read
from or written to a source or destination.
Java offers two types of streams:
➢character streams
➢byte streams.
Character Streams
• Character streams are designed to address
character based records, which includes textual
records inclusive of letters, digits, symbols, and
other characters.
• These streams are represented by way of training
that quit with the phrase "Reader" or "Writer" of
their names, inclusive of FileReader,
BufferedReader, FileWriter, and BufferedWriter.
• Character streams offer a convenient manner to read
and write textual content-primarily based information
due to the fact they mechanically manage character
encoding and decoding.
Byte Streams
• Byte streams are designed to deal with raw binary
data, which includes all kinds of data, including
characters, pictues, audio, and video.
• These streams are represented through cclasses
that cease with the word "InputStream" or
"OutputStream" of their names,along with
FileInputStream,BufferedInputStream,
FileOutputStream and BufferedOutputStream.
• Byte streams offer a low-stage interface for
studying and writing character bytes or blocks of
bytes.
• They are normally used for coping with non-
textual statistics, studying and writing files of their
binary form, and running with network sockets.
Difference between Character Stream and Byte Stream in Java
Text vs non-Text data Text-based data, strings Binary data, images, audio,
video
Performance Additional conversion may Efficient for handling
impact performance large binary data
System.out.println("simple message");
System.err.println("error message");
OutputStream
Java application uses an output stream to write
data to a destination, it may be a file,an
array,peripheral device or socket.
InputStream
Java application uses an input stream to read
data from a source, it may be a file,an
array,peripheral device or socket.
Working of Java OutputStream and InputStream
OutputStream class
• OutputStream class is an abstract class. It is the
super class of all classes representing an output
stream of bytes. An output stream accepts output
bytes and sends them to some sink.
InputStream class
• InputStream class is an abstract class. It is the
super class of all classes representing an input
stream of bytes.
Commonly used methods of InputStream class
FileInputStream and FileOutputStream (File Handling)
Unit 2
Lecture 18
Lecture 18
• Thread
• Thread Life Cycle
Multithreading in Java
• Multithreading in java is a process of
executing multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a
smallest unit of processing.
• Java Multithreading is mostly used in games,
animation etc.
Advantages of Java Multithreading
1) It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.
2) You can perform many operations together
so it saves time.
3) Threads are independent so it doesn't affect
other threads if exception occur in a single
thread.
What is Thread in java
• A thread is a lightweight sub process, a
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 shares a common memory area.
Note: At a time one thread is executed only.
Life cycle of a Thread (Thread States)
The life cycle of the thread in java is controlled
by JVM. The java thread states are as follows:
• New
• Runnable
• Running
• Non-Runnable (Blocked)
• Terminated
1) New
The thread is in new state if you create an instance of
Thread class but before the invocation of start()
method.
2) Runnable
The thread is in runnable state after invocation of start()
method, but the thread scheduler has not selected it to
be the running thread.
3) Running
The thread is in running state if the thread scheduler has
selected it.
4) Non-Runnable (Blocked)
This is the state when the thread is still alive, but is
currently not eligible to run.
5) Terminated
A thread is in terminated or dead state when its run()
method exits.
Object Oriented Programming with Java
(Subject Code: BCS-403)
Unit 2
Lecture 19
Lecture 19
• Creating Threads
• Thread Priorities
How to create thread
There are two ways to create a thread:
• By extending Thread class
• By implementing Runnable interface.
Commonly used methods of Thread class:
• public void run(): is used to perform action for a
thread.
• public void start(): starts the execution of the
thread.JVM calls the run() method on the thread.
• public void sleep(long miliseconds): Causes the
currently executing thread to sleep (temporarily
cease execution) for the specified number of
milliseconds.
• public int getPriority(): returns the priority of the
thread.
• public int setPriority(int priority): changes the
priority of the thread.
• public String getName(): returns the name of
the thread.
• public void setName(String name): changes
the name of the thread.
• public Thread currentThread(): returns the
reference of currently executing thread.
• public boolean isAlive(): tests if the thread is
alive.
• public void yield(): causes the currently
executing thread object to temporarily pause
and allow other threads to execute.
Starting a thread
• start() method of Thread class is used to start
a newly created thread. It performs following
tasks:A new thread starts(with new callstack).
• The thread moves from New state to the
Runnable state.
• When the thread gets a chance to execute, its
target run() method will run.
Java Thread Example by extending Thread class
class Multi extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Java Thread Example by implementing Runnable interface
t1.start();
t2.start();
t1.setName(“CSA Webtech");
System.out.println("After changing name of t1:"+t1.getName());
}
}
Priority of a Thread (Thread Priority)
• Each thread have a priority.
• Priorities are represented by a number
between 1 and 10.
• In most cases, thread schedular schedules the
threads according to their priority (known as
preemptive scheduling). But it is not
guaranteed because it depends on JVM
specification that which scheduling it chooses.
Three constants defined in Thread class
• public static int MIN_PRIORITY
• public static int NORM_PRIORITY
• public static int MAX_PRIORITY
Note: Default priority of a thread is 5
(NORM_PRIORITY). The value of MIN_PRIORITY is 1
and the value of MAX_PRIORITY is 10.
class TestMultiPriority1 extends Thread{
public void run(){
System.out.println("running thread name is:"+Thread.currentT
hread().getName());
System.out.println("running thread priority is:"+Thread.current
Thread().getPriority());
}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}}
Object Oriented Programming with Java
(Subject Code: BCS-403)
Unit 2
Lecture 20
Lecture 20
• Synchronizing Threads
• Inter-thread Communication
Synchronizing Threads
• Multi-threaded programs may often come to a
situation where multiple threads try to access
the same resources and finally produce
erroneous and unforeseen results.
• In order to overcome this problem, we have
thread synchronization.