SlideShare a Scribd company logo
JAVA PROGRAMMING- Exception
handling - Multithreading
Dr R Jegadeesan Prof-CSE
Jyothishmathi Institute of Technology and Science,
Karimnagar
SYLLABUS
Exception handling - Fundamentals of exception handling, Exception
types, Termination or resumptive models, Uncaught exceptions, using
try and catch, multiple catch clauses, nested try statements, throw,
throws and finally, built- in exceptions, creating own exception sub
classes.
Multithreading- Differences between thread-based multitasking and
process-based multitasking, Java thread model, creating threads,
thread priorities, synchronizing threads, inter thread communication
UNIT 3 : Exception Handling and Multithreading
Topic Name : Fundamentals of exception handling and introduction to multithreading
Topic :Basic concepts of Exception handling and multithreading
Aim & Objective : To make the student understand the concept of Exception handling
and multithreading.
Application With Example : Java program to handle checked and unchecked
exceptions.
Limitations If Any :
Reference Links :
• Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pv
Ltd.
• https://www.geeksforgeeks.org/multithreading-in-java/
•Video Link details
•https://www.youtube.com/watch?v=W-N2ltgU-X4
•https://www.youtube.com/watch?v=p-WcHj5GrYE
Universities & Important Questions :
• How many Exceptions we can define in ‘throws’ clause?
• What are errors?
• What are exceptions?
• How can bugs be removed?
• Distinguish between synchronous and asynchronous exceptions.
• Distinguish between checked and unchecked exceptions.
• Explain uncaught exceptions
• How to display the description of an exception.
• Explain the uses of multiple catch clauses
• Explain nested try statements.
• Explain Java’s built-in exceptions
• List out the differences between multithreading and multitasking
• What is a thread? Explain the concept of a multithread programming.
• Define multithreading. Give an example of an application that needs multithreading.
• Explain the various methods defined by the thread class with examples of each.
• How do we set priorities for thread?
• Write a program that demonstrates the priorities setting in thread.
• What is synchronization? Explain with suitable example.
• How is interthread communication achieved?
• Explain interthread communication with an example.
• What is thread group? Explain its importance with a program
▪ Exception handling concepts
▪ Exception types
▪ Uncaught exceptions
▪ Try, catch, throw, throws, finally clauses
▪ Creating own exceptions
▪ Threadbased and processbased multitasking
▪ Java thread model
▪ Creating threads
▪ Synchronizing threads
▪ Inter Thread communication
UNIT – III
CONTENTS
Exception
When an exceptional
condition arises, an object
representing that exception is
created and thrown in the
method that caused the error.
Diagrammatic Representation of Program
Execution
Java
Interp
reter
java
r Exception
Program
Execution
No
Errors
Error o
Exception Type determined
Object of Exception Class created
Related message displayed
Java Code classes.zip: classes needed at run-
time by Java Interpreter
Exception Classes
Java Compiler
javac
Bytecode
•Exceptions can be generated by: Java
run-time system:-
ERROR
Generated by the code:-
EXCEPTION
THROWABLE
❖All Exception types are
subclasses of the built-in
class THROWABLE.
❖THROWABLE is at the top of
the Exception class
Hierarchy.
Exception Types
Throwable
Exception Error
Stack overflow
ArrayIndexOutOfBounds
Run-time
Exception
ClassNotFound
Linkage
Error
Uncaught
Exceptions
• class UncaughtEx{
• public static void main(String args[]) {
• int d = 0; int a =
42/d;
• } }
• Output : java.lang.ArithmeticException:/by zero
• at Exc0.main(UncaughtEx.java:4)
Five keywords
Java exception-handling
❖try
❖catch
❖throw
❖throws
❖ finally
Exception-Handling ...
❖Program statements to be
monitored for exceptions are
contained within a try block.
❖Your code can catch this
exception using catch and
handle it in some rational
manner.
throw to
❖Use the keyword
throw an exception.
❖Any exception that is thrown
out of a method throws
clause.
❖Any code that absolutely
must be executed is put in a
finally block.
class HandledException{
public static void main(String args[])
{ int d, a ;
try { d = 0;a = 42 /d; }
catch(ArithmeticException e)
{System.out.println(“Division by 0”);}
} }
Output: Division by 0
Using try and catch
• Advantages of handling
exceptions:
•Itallows the programmer to fix the
error
•Prevents the program from
automatically terminating
try-catch Control Flow
code before try
exception occurs
try block catch block
code after try
try-catch Control Flow
code before try
try block
code after try
no exceptions occur
catch block
exception occurs
Multiple catch clauses
❖One block of code causes
multiple Exception.
❖Two or more catch clauses.
➢Exception subclass must
come before any of their super
classes.
➢Unreachable code.
public static void main(String args[]) {
try { int a = args.length;
int b = 42 / a;
int c[ ] = {1}; c[42] = 99; }
catch(ArithmeticException e)
{System.out.println(“Divide by 0: “ + e ); }
catch(ArrayIndexOutOfBoundsException e)
{System.out.println(“Array index oob: “ + e);}
System.out.println(“After try/catch block”);}
Nested try Statements
❖A try and its catch can be
nested inside the block of
another try.
❖It executes until one of the
catch statements succeeds or
Java run-time system handle
the exception.
try{ int a=args.length;
int b=42/a;
try{int c[ ]={1},c[40]=99;}
catch(ArrayIndexOutOfBoudnds
Exception e)
{System.out.println(e); }
}
catch(ArithmeticExceptione)
{}
The finally Clause
❖finally creates
code that will
a block of
be executed
(whether or not an exception
is thrown)
class FinallyDemo {
int [ ] num1= {12, 16, 10, 8, -1, 6};
int [ ] num2 = { 1, 5, 35, 20, 1, 13};
public static void main(String [ ] args) {
FinallyDemo f = new FinallyDemo( );
f.readNums(f.num1);
f.readNums(f.num2);}
void readNums(int [ ] array) {
int count = 0, last = 0 ;
try {
while (count < array.length) {
last = array[count++];
if (last == -1) return; }}
finally
{System.out.println(“Last” +
last);}
try-catch Control Flow
try block
exception occurs
code after try
code before try
finally block (if it exists)
catch block
The throw
clause
❖Throw an exception explicitly.
throw ThrowableInstance
Throwable object:
➢Using a parameter into a catch
clause
➢ Creating one with the new
operator.
class ThrowDemo {
static void demoproc( ){
try { throw new
NullpointerException(“demo”);}
catch(NullPointerException e) {
System.out.println(“demoproc.”);
throw e;} }
// Output: demoproc
Continued…
public static void main(Stringargs[])
{try { demoproc();}
catch(NullPointerException e)
{System.out.println(“Recaught”+e);}
} }
//Recaught:java.lang.NullPointerEx
ception: demo
Exam
ple
The throws clause
❖A throws :-Is used to throw a
Exception that is not handled.
❖Error and RuntimeException
or any of their subclasses
don’t use throws.
The throws clause -continued
❖Type method-name
(parameter-list) throws
exception-list
{ // body of method }
31
class ThrowsDemo {
static void throwProc( ) throws
IIlegalAccessException { throw new
IllegalAccessException(“demo”);
}
public static void main (String args[] ) {
try { throwProc( );}
catch(IllegalAccessException e){
System.out.println(“Caught ” + e);}}
}
Java’s Built-in Exceptions
❖Java defines several
exception classes inside the
standard package java.lang
• RuntimeException or Error
Unchecked Exceptions
Unchecked Exception = Runtime
Exceptions/ERROR
Example:
•NumberFormatException
•IllegalArgumentException
•OutOfMemoryError
Checked
Exceptions
Checked Exception = checked at
compile time
These errors are due to
external circumstances that
the programmer cannot
prevent
Example:-IOException
Java’s Built-in
Exceptions ...
The following are Java’s Checked
Exceptions:
❖ClassNotFoundException
❖CloneNotSupportedException
❖IllegalAccessException
❖InstantiationException
❖InterruptedException
❖NoSuchFieldException
❖NoSuchMethodException
Creating Your Own Exception
Classes
❖All user-created exceptions –
subclass of Exception
❖All methods inherited
Throwable.
Demo of ExcepDemo.java
class YourException extendsException
{ private int detail;
YourException(int a)
{ detail = a; }
public String toString( )
{return “YourException[“ + detail +”]”; }
}
class ExcepDemo {
static void compute(int a)
throwsYourException
{
if( a > 10)
throw newYourException(a);
System.out.println(“Normal Exit”)
}
ExcepDemo.j
ava ...
public static void main
(String args[ ]){
try { compute(1); compute(20);}
catch(YourException e)
{System.out.println(“Caught“+e)}
} }
Output:
Called compute(1)
Normal exit
Called compute(20)
Caught YourException[20]
Threads
• Threads are lightweight processes as the
overhead of switching between threads is less
• The can be easily spawned
• The Java Virtual Machine spawns a thread
when your program is run called the Main
Thread
Why do we need threads?
• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the
requests processing would be in a queue, thus
increasing the response time and also might hang
the server if there was a bad request.
• By implementing in a multithreaded environment,
the web server can serve multiple request
simultaneously thus improving response time
Creating threads
• In java threads can be created by extending
the Thread class or implementing the
Runnable Interface
• It is more preferred to implement the
Runnable Interface so that we can extend
properties from other classes
• Implement the run() method which is the
starting point for thread execution
Running threads
• Example
class mythread implements Runnable{
public void run(){
System.out.println(“Thread Started”);
}
}
class mainclass {
public static void main(String args[]){
Thread t = new Thread(new mythread()); // This is the way to instantiate a
thread implementing runnable interface
t.start(); // starts the thread by running the run method
}
}
• Calling t.run() does not start a thread, it is just a simple
method call.
• Creating an object does not create a thread, calling
start() method creates the thread.
Synchronization
• Synchronization is prevent data corruption
• Synchronization allows only one thread to
perform an operation on a object at a time.
• If multiple threads require an access to an
object, synchronization helps in maintaining
consistency.
Example
public class Counter{
private int count = 0;
public int getCount(){
return count;
}
public setCount(int count){
this.count = count;
}
}
• In this example, the counter tells how many an access has been made.
• If a thread is accessing setCount and updating count and another thread is accessing
getCount at the same time, there will be inconsistency in the value of count.
Fixing the example
public class Counter{
private static int count = 0;
public synchronized int getCount(){
return count;
}
public synchoronized setCount(int count){
this.count = count;
}
}
• By adding the synchronized keyword we make sure that when one thread is in the setCount
method the other threads are all in waiting state.
• The synchronized keyword places a lock on the object, and hence locks all the other methods
which have the keyword synchronized. The lock does not lock the methods without the
keyword synchronized and hence they are open to access by other threads.
What about static methods?
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public static synchronized setCount(int count){
this.count = count;
}
}
• In this example the methods are static and hence are associated with the class object and not
the instance.
• Hence the lock is placed on the class object that is, Counter.class object and not on the
object itself. Any other non static synchronized methods are still available for access by other
threads.
Common Synchronization mistake
public class Counter{
private int count = 0;
public static synchronized int getCount(){
return count;
}
public synchronized setCount(int count){
this.count = count;
}
}
• The common mistake here is one method is static synchronized and another method is non
static synchronized.
• This makes a difference as locks are placed on two different objects. The class object and the
instance and hence two different threads can access the methods simultaneously.
Object locking
• The object can be explicitly locked in this way
synchronized(myInstance){
try{
wait();
}catch(InterruptedException ex){
}
System.out.println(“Iam in this “);
notifyAll();
}
• The synchronized keyword locks the object. The wait keyword waits for the
lock to be acquired, if the object was already locked by another thread.
Notifyall() notifies other threads that the lock is about to be released by the
current thread.
• Another method notify() is available for use, which wakes up only the next
thread which is in queue for the object, notifyall() wakes up all the threads
and transfers the lock to another thread having the highest priority.
Thank you

More Related Content

What's hot (20)

JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
shanmuga rajan
 
Java awt (abstract window toolkit)
Java awt (abstract window toolkit)Java awt (abstract window toolkit)
Java awt (abstract window toolkit)
Elizabeth alexander
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Applets
AppletsApplets
Applets
Prabhakaran V M
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Exception handling
Exception handlingException handling
Exception handling
PhD Research Scholar
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Collection Framework in java
Collection Framework in javaCollection Framework in java
Collection Framework in java
CPD INDIA
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
kamal kotecha
 
Wrapper class
Wrapper classWrapper class
Wrapper class
kamal kotecha
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Java I/O
Java I/OJava I/O
Java I/O
Jussi Pohjolainen
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 

Similar to JAVA PROGRAMMING- Exception handling - Multithreading (20)

JAVA UNIT 2
JAVA UNIT 2JAVA UNIT 2
JAVA UNIT 2
Dr. SURBHI SAROHA
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Exception
ExceptionException
Exception
abhay singh
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
KALAISELVI P
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Tony Nguyen
 
Exception
ExceptionException
Exception
Hoang Nguyen
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Fraboni Ec
 
Exception
ExceptionException
Exception
Young Alista
 
Exception
ExceptionException
Exception
James Wong
 
Exception
ExceptionException
Exception
Luis Goldster
 
Exception
ExceptionException
Exception
Harry Potter
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
KALAISELVI P
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Ad

More from Jyothishmathi Institute of Technology and Science Karimnagar (20)

JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing ButtonsJAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O
Jyothishmathi Institute of Technology and Science Karimnagar
 
Java programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- InheritanceJava programming -Object-Oriented Thinking- Inheritance
Java programming -Object-Oriented Thinking- Inheritance
Jyothishmathi Institute of Technology and Science Karimnagar
 
WEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScriptWEB TECHNOLOGIES JavaScript
WEB TECHNOLOGIES JavaScript
Jyothishmathi Institute of Technology and Science Karimnagar
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
Jyothishmathi Institute of Technology and Science Karimnagar
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
Jyothishmathi Institute of Technology and Science Karimnagar
 
WEB TECHNOLOGIES XML
WEB TECHNOLOGIES XMLWEB TECHNOLOGIES XML
WEB TECHNOLOGIES XML
Jyothishmathi Institute of Technology and Science Karimnagar
 
WEB TECHNOLOGIES- PHP Programming
WEB TECHNOLOGIES-  PHP ProgrammingWEB TECHNOLOGIES-  PHP Programming
WEB TECHNOLOGIES- PHP Programming
Jyothishmathi Institute of Technology and Science Karimnagar
 
Compiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent OptimizationsCompiler Design- Machine Independent Optimizations
Compiler Design- Machine Independent Optimizations
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time EnvironmentsCOMPILER DESIGN Run-Time Environments
COMPILER DESIGN Run-Time Environments
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed TranslationCOMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Syntax Directed Translation
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax AnalysisCOMPILER DESIGN- Syntax Analysis
COMPILER DESIGN- Syntax Analysis
Jyothishmathi Institute of Technology and Science Karimnagar
 
COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis: COMPILER DESIGN- Introduction & Lexical Analysis:
COMPILER DESIGN- Introduction & Lexical Analysis:
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail SecurityCRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level SecurityCRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash FunctionsCRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key CiphersCRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
Jyothishmathi Institute of Technology and Science Karimnagar
 
CRYPTOGRAPHY & NETWORK SECURITY
CRYPTOGRAPHY & NETWORK SECURITYCRYPTOGRAPHY & NETWORK SECURITY
CRYPTOGRAPHY & NETWORK SECURITY
Jyothishmathi Institute of Technology and Science Karimnagar
 
Computer Forensics Working with Windows and DOS Systems
Computer Forensics Working with Windows and DOS SystemsComputer Forensics Working with Windows and DOS Systems
Computer Forensics Working with Windows and DOS Systems
Jyothishmathi Institute of Technology and Science Karimnagar
 
Ad

Recently uploaded (20)

Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Trends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary MeekerTrends Artificial Intelligence - Mary Meeker
Trends Artificial Intelligence - Mary Meeker
Clive Dickens
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free DownloadViral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Integration of Utility Data into 3D BIM Models Using a 3D Solids Modeling Wor...
Safe Software
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025TimeSeries Machine Learning - PyData London 2025
TimeSeries Machine Learning - PyData London 2025
Suyash Joshi
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Cisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdfCisco ISE Performance, Scalability and Best Practices.pdf
Cisco ISE Performance, Scalability and Best Practices.pdf
superdpz
 
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
“Solving Tomorrow’s AI Problems Today with Cadence’s Newest Processor,” a Pre...
Edge AI and Vision Alliance
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 

JAVA PROGRAMMING- Exception handling - Multithreading

  • 1. JAVA PROGRAMMING- Exception handling - Multithreading Dr R Jegadeesan Prof-CSE Jyothishmathi Institute of Technology and Science, Karimnagar
  • 2. SYLLABUS Exception handling - Fundamentals of exception handling, Exception types, Termination or resumptive models, Uncaught exceptions, using try and catch, multiple catch clauses, nested try statements, throw, throws and finally, built- in exceptions, creating own exception sub classes. Multithreading- Differences between thread-based multitasking and process-based multitasking, Java thread model, creating threads, thread priorities, synchronizing threads, inter thread communication
  • 3. UNIT 3 : Exception Handling and Multithreading Topic Name : Fundamentals of exception handling and introduction to multithreading Topic :Basic concepts of Exception handling and multithreading Aim & Objective : To make the student understand the concept of Exception handling and multithreading. Application With Example : Java program to handle checked and unchecked exceptions. Limitations If Any : Reference Links : • Java The complete reference, 9th edition, Herbert Schildt, McGraw Hill Education (India) Pv Ltd. • https://www.geeksforgeeks.org/multithreading-in-java/ •Video Link details •https://www.youtube.com/watch?v=W-N2ltgU-X4 •https://www.youtube.com/watch?v=p-WcHj5GrYE
  • 4. Universities & Important Questions : • How many Exceptions we can define in ‘throws’ clause? • What are errors? • What are exceptions? • How can bugs be removed? • Distinguish between synchronous and asynchronous exceptions. • Distinguish between checked and unchecked exceptions. • Explain uncaught exceptions • How to display the description of an exception. • Explain the uses of multiple catch clauses • Explain nested try statements. • Explain Java’s built-in exceptions • List out the differences between multithreading and multitasking • What is a thread? Explain the concept of a multithread programming. • Define multithreading. Give an example of an application that needs multithreading. • Explain the various methods defined by the thread class with examples of each. • How do we set priorities for thread? • Write a program that demonstrates the priorities setting in thread. • What is synchronization? Explain with suitable example. • How is interthread communication achieved? • Explain interthread communication with an example. • What is thread group? Explain its importance with a program
  • 5. ▪ Exception handling concepts ▪ Exception types ▪ Uncaught exceptions ▪ Try, catch, throw, throws, finally clauses ▪ Creating own exceptions ▪ Threadbased and processbased multitasking ▪ Java thread model ▪ Creating threads ▪ Synchronizing threads ▪ Inter Thread communication UNIT – III CONTENTS
  • 6. Exception When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error.
  • 7. Diagrammatic Representation of Program Execution Java Interp reter java r Exception Program Execution No Errors Error o Exception Type determined Object of Exception Class created Related message displayed Java Code classes.zip: classes needed at run- time by Java Interpreter Exception Classes Java Compiler javac Bytecode
  • 8. •Exceptions can be generated by: Java run-time system:- ERROR Generated by the code:- EXCEPTION
  • 9. THROWABLE ❖All Exception types are subclasses of the built-in class THROWABLE. ❖THROWABLE is at the top of the Exception class Hierarchy.
  • 10. Exception Types Throwable Exception Error Stack overflow ArrayIndexOutOfBounds Run-time Exception ClassNotFound Linkage Error
  • 11. Uncaught Exceptions • class UncaughtEx{ • public static void main(String args[]) { • int d = 0; int a = 42/d; • } } • Output : java.lang.ArithmeticException:/by zero • at Exc0.main(UncaughtEx.java:4)
  • 13. Exception-Handling ... ❖Program statements to be monitored for exceptions are contained within a try block. ❖Your code can catch this exception using catch and handle it in some rational manner.
  • 14. throw to ❖Use the keyword throw an exception. ❖Any exception that is thrown out of a method throws clause. ❖Any code that absolutely must be executed is put in a finally block.
  • 15. class HandledException{ public static void main(String args[]) { int d, a ; try { d = 0;a = 42 /d; } catch(ArithmeticException e) {System.out.println(“Division by 0”);} } } Output: Division by 0
  • 16. Using try and catch • Advantages of handling exceptions: •Itallows the programmer to fix the error •Prevents the program from automatically terminating
  • 17. try-catch Control Flow code before try exception occurs try block catch block code after try
  • 18. try-catch Control Flow code before try try block code after try no exceptions occur catch block exception occurs
  • 19. Multiple catch clauses ❖One block of code causes multiple Exception. ❖Two or more catch clauses. ➢Exception subclass must come before any of their super classes. ➢Unreachable code.
  • 20. public static void main(String args[]) { try { int a = args.length; int b = 42 / a; int c[ ] = {1}; c[42] = 99; } catch(ArithmeticException e) {System.out.println(“Divide by 0: “ + e ); } catch(ArrayIndexOutOfBoundsException e) {System.out.println(“Array index oob: “ + e);} System.out.println(“After try/catch block”);}
  • 21. Nested try Statements ❖A try and its catch can be nested inside the block of another try. ❖It executes until one of the catch statements succeeds or Java run-time system handle the exception.
  • 22. try{ int a=args.length; int b=42/a; try{int c[ ]={1},c[40]=99;} catch(ArrayIndexOutOfBoudnds Exception e) {System.out.println(e); } } catch(ArithmeticExceptione) {}
  • 23. The finally Clause ❖finally creates code that will a block of be executed (whether or not an exception is thrown)
  • 24. class FinallyDemo { int [ ] num1= {12, 16, 10, 8, -1, 6}; int [ ] num2 = { 1, 5, 35, 20, 1, 13}; public static void main(String [ ] args) { FinallyDemo f = new FinallyDemo( ); f.readNums(f.num1); f.readNums(f.num2);}
  • 25. void readNums(int [ ] array) { int count = 0, last = 0 ; try { while (count < array.length) { last = array[count++]; if (last == -1) return; }} finally {System.out.println(“Last” + last);}
  • 26. try-catch Control Flow try block exception occurs code after try code before try finally block (if it exists) catch block
  • 27. The throw clause ❖Throw an exception explicitly. throw ThrowableInstance Throwable object: ➢Using a parameter into a catch clause ➢ Creating one with the new operator.
  • 28. class ThrowDemo { static void demoproc( ){ try { throw new NullpointerException(“demo”);} catch(NullPointerException e) { System.out.println(“demoproc.”); throw e;} } // Output: demoproc
  • 29. Continued… public static void main(Stringargs[]) {try { demoproc();} catch(NullPointerException e) {System.out.println(“Recaught”+e);} } } //Recaught:java.lang.NullPointerEx ception: demo
  • 31. The throws clause ❖A throws :-Is used to throw a Exception that is not handled. ❖Error and RuntimeException or any of their subclasses don’t use throws.
  • 32. The throws clause -continued ❖Type method-name (parameter-list) throws exception-list { // body of method }
  • 33. 31 class ThrowsDemo { static void throwProc( ) throws IIlegalAccessException { throw new IllegalAccessException(“demo”); } public static void main (String args[] ) { try { throwProc( );} catch(IllegalAccessException e){ System.out.println(“Caught ” + e);}} }
  • 34. Java’s Built-in Exceptions ❖Java defines several exception classes inside the standard package java.lang • RuntimeException or Error
  • 35. Unchecked Exceptions Unchecked Exception = Runtime Exceptions/ERROR Example: •NumberFormatException •IllegalArgumentException •OutOfMemoryError
  • 36. Checked Exceptions Checked Exception = checked at compile time These errors are due to external circumstances that the programmer cannot prevent Example:-IOException
  • 37. Java’s Built-in Exceptions ... The following are Java’s Checked Exceptions: ❖ClassNotFoundException ❖CloneNotSupportedException ❖IllegalAccessException ❖InstantiationException ❖InterruptedException ❖NoSuchFieldException ❖NoSuchMethodException
  • 38. Creating Your Own Exception Classes ❖All user-created exceptions – subclass of Exception ❖All methods inherited Throwable.
  • 39. Demo of ExcepDemo.java class YourException extendsException { private int detail; YourException(int a) { detail = a; } public String toString( ) {return “YourException[“ + detail +”]”; } }
  • 40. class ExcepDemo { static void compute(int a) throwsYourException { if( a > 10) throw newYourException(a); System.out.println(“Normal Exit”) }
  • 41. ExcepDemo.j ava ... public static void main (String args[ ]){ try { compute(1); compute(20);} catch(YourException e) {System.out.println(“Caught“+e)} } }
  • 42. Output: Called compute(1) Normal exit Called compute(20) Caught YourException[20]
  • 43. Threads • Threads are lightweight processes as the overhead of switching between threads is less • The can be easily spawned • The Java Virtual Machine spawns a thread when your program is run called the Main Thread
  • 44. Why do we need threads? • To enhance parallel processing • To increase response to the user • To utilize the idle time of the CPU • Prioritize your work depending on priority
  • 45. Example • Consider a simple web server • The web server listens for request and serves it • If the web server was not multithreaded, the requests processing would be in a queue, thus increasing the response time and also might hang the server if there was a bad request. • By implementing in a multithreaded environment, the web server can serve multiple request simultaneously thus improving response time
  • 46. Creating threads • In java threads can be created by extending the Thread class or implementing the Runnable Interface • It is more preferred to implement the Runnable Interface so that we can extend properties from other classes • Implement the run() method which is the starting point for thread execution
  • 47. Running threads • Example class mythread implements Runnable{ public void run(){ System.out.println(“Thread Started”); } } class mainclass { public static void main(String args[]){ Thread t = new Thread(new mythread()); // This is the way to instantiate a thread implementing runnable interface t.start(); // starts the thread by running the run method } } • Calling t.run() does not start a thread, it is just a simple method call. • Creating an object does not create a thread, calling start() method creates the thread.
  • 48. Synchronization • Synchronization is prevent data corruption • Synchronization allows only one thread to perform an operation on a object at a time. • If multiple threads require an access to an object, synchronization helps in maintaining consistency.
  • 49. Example public class Counter{ private int count = 0; public int getCount(){ return count; } public setCount(int count){ this.count = count; } } • In this example, the counter tells how many an access has been made. • If a thread is accessing setCount and updating count and another thread is accessing getCount at the same time, there will be inconsistency in the value of count.
  • 50. Fixing the example public class Counter{ private static int count = 0; public synchronized int getCount(){ return count; } public synchoronized setCount(int count){ this.count = count; } } • By adding the synchronized keyword we make sure that when one thread is in the setCount method the other threads are all in waiting state. • The synchronized keyword places a lock on the object, and hence locks all the other methods which have the keyword synchronized. The lock does not lock the methods without the keyword synchronized and hence they are open to access by other threads.
  • 51. What about static methods? public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public static synchronized setCount(int count){ this.count = count; } } • In this example the methods are static and hence are associated with the class object and not the instance. • Hence the lock is placed on the class object that is, Counter.class object and not on the object itself. Any other non static synchronized methods are still available for access by other threads.
  • 52. Common Synchronization mistake public class Counter{ private int count = 0; public static synchronized int getCount(){ return count; } public synchronized setCount(int count){ this.count = count; } } • The common mistake here is one method is static synchronized and another method is non static synchronized. • This makes a difference as locks are placed on two different objects. The class object and the instance and hence two different threads can access the methods simultaneously.
  • 53. Object locking • The object can be explicitly locked in this way synchronized(myInstance){ try{ wait(); }catch(InterruptedException ex){ } System.out.println(“Iam in this “); notifyAll(); } • The synchronized keyword locks the object. The wait keyword waits for the lock to be acquired, if the object was already locked by another thread. Notifyall() notifies other threads that the lock is about to be released by the current thread. • Another method notify() is available for use, which wakes up only the next thread which is in queue for the object, notifyall() wakes up all the threads and transfers the lock to another thread having the highest priority.