Module 3 - Java Programming
Module 3 - Java Programming
• Exception Handling
– Exceptions & Errors
– Types of Exception
– Control Flow in Exceptions
– Use of try, catch, throw, throws, finally, in
Exception Handling
– User Defined Exceptions
Error
• Errors are beyond the control of the
programmers.
• The errors cannot be recovered which means
we cannot handle it through the program. To
avoid the error, the programmer must follow
the rules of the particular programming
language.
• These are the problems raised in the program
at compile time. For example, the syntactical
mistake (missing semicolon, exclamatory
symbol, misspelling the keyword) is the best
example of an error and these problems are
identified during the compilation time.
Exceptions
• Exceptions are abnormal conditions in a
program which leads to abort the program.
• Runtime error in the program and it can be
recovered. It means, we can handle the
exception through the program.
• An unexpected event that abrupt the normal
execution of the program is called exception.
• package exception; • }
• }
• // class representing custom exception •
• class InvalidAgeException extends Exception • // main method
• { • public static void main(String args[])
• public InvalidAgeException (String str) • {
• { • try
• // calling the constructor of parent Exception • {
• super(str); • // calling the method
• } • validate(13);
• } • }
• // class that uses custom exception • catch (InvalidAgeException ex)
InvalidAgeException • {
• public class TestCustomException1 • System.out.println("Caught the exception");
• { •
• // method to check the age • // printing the message from
• static void validate (int age) throws InvalidAgeException object
InvalidAgeException{ • System.out.println("Exception occured: " +
• if(age < 18){ ex);
• // throw an object of user defined exception • }
• throw new InvalidAgeException("age is not •
valid to vote"); • System.out.println("rest of the code...");
• }
Output
Throwable
User defined exception using throw
Multithreading
Multithreading
• Multithreading in java is a process of executing
multiple threads simultaneously.
• A Multi threaded program contains two or more parts
that can run concurrently.
• Each part of a program is called a thread.
• Multi threading is a specialized form of multi tasking.
Multitasking Fundamentals
• Multitasking is a process of executing multiple tasks
simultaneously.
• We use multitasking to utilize the CPU.
Multitasking can be achieved by two ways:
• Process-based Multitasking(Multiprocessing)
• Thread-based Multitasking(Multithreading)
Multi Threading Fundamentals
Process based multi tasking:
• A feature that allows to execute two or more programs
concurrently.
• Here a program is the smallest unit of code that can be dispatched
by the scheduler.
Eg: running the java compiler, using text editor or browsing the
internet simultaneously…
Thread based Multitasking:
• Here the thread is Smallest unit of dispatchable code.
• single program can perform two or more tasks at once.
Eg: a text editor can be formatting text at the same time that it is
printing, as long as these two actions are being performed by two
separate threads.
Process-based vs. Thread-based
2. Processes are heavy weight tasks 2. Threads are light weight process.
that require their own separate They share the same address space
address spaces.
3. Interprocess communication is
3. Inter thread communication is
expensive and limited.
inexpensive.
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}
}
Runnable Interfaces
Output
Creating A Thread :By Extending Thread
class
General form:
class classname extends Thread{
public void run(){ //write code here}
}
class Tdemo{
public static void main(String args[]){
//create the object for above class say t1
//call start() method of Thread class
t1.start();
}
}
Creating A Thread :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();
}
}
Output:
• thread is running….
Output
Extending Thread vs Implementing Runnable
interface
Extending Thread Implementing Runnable interface
class A extends Thread Class A implements runnable
{ public void run() { } } {public void run() { }
class Ademo{ }
A a1=new A(); Class Ademo{
a1.start(); A a1=new A();
} Thread t=new Thread(a1);
t1.start();}
We can override the other methods of We can only implement only run
thread also along with run(). method.
We can not inherit other classes. We can inherit other classes also.
Methods in Thread class
• currentThread() method returns a reference
to the currently executing thread object.
• getName() method returns this thread's name.
Method Description
setName() to give thread a name
getName() return thread's name
getPriority() return thread's priority
isAlive() checks if thread is still running or
not
join() Wait for a thread to end
run() Entry point for a thread
sleep() suspend thread for a specified
time
start() start a thread by calling run()
method
Constructors of Thread class
• Thread ( )
• Thread ( String str )
• Thread ( Runnable r )
Thread Class Constructors
1. Thread() Allocates a new Thread Object.
E.g., Thread t=new Thread();
3. Thread(Runnable target)
E.g: SecondThread st= new SecondThread();
Thread t=new Thread(st);
• In most cases, thread scheduler schedules the threads according to their priority (known
as preemptive scheduling).