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

PPSX
Exception Handling
PPTX
Exception handling in Java
PPT
Java access modifiers
PDF
Exception handling
PPTX
Interface in java ,multiple inheritance in java, interface implementation
PPTX
Critical Section in Operating System
PDF
Constructor and Destructor
PPT
Exception Handling in JAVA
Exception Handling
Exception handling in Java
Java access modifiers
Exception handling
Interface in java ,multiple inheritance in java, interface implementation
Critical Section in Operating System
Constructor and Destructor
Exception Handling in JAVA

What's hot (20)

PPTX
Exception handling in Java
PPTX
Control Statements in Java
PPTX
Notes on Debugging
PPTX
C tokens
PPT
PPT
Abstract class
PDF
PPTX
Multi-threaded Programming in JAVA
PPTX
CONDITIONAL STATEMENT IN C LANGUAGE
PPT
Exception handling in java
PPTX
Exception Handling in C++
PPTX
Error and exception in python
PPTX
Exception handling in java
PPT
C++: Constructor, Copy Constructor and Assignment operator
PPTX
Deadlocks in operating system
PPTX
Java interface
PPTX
interface in c#
PPTX
Virtual function in C++ Pure Virtual Function
PPT
Java interfaces & abstract classes
PDF
Java - Interfaces & Packages
Exception handling in Java
Control Statements in Java
Notes on Debugging
C tokens
Abstract class
Multi-threaded Programming in JAVA
CONDITIONAL STATEMENT IN C LANGUAGE
Exception handling in java
Exception Handling in C++
Error and exception in python
Exception handling in java
C++: Constructor, Copy Constructor and Assignment operator
Deadlocks in operating system
Java interface
interface in c#
Virtual function in C++ Pure Virtual Function
Java interfaces & abstract classes
Java - Interfaces & Packages
Ad

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

PPTX
Unit II Java & J2EE regarding Java application development
PPTX
JAVA UNIT 2
PPTX
UNIT-3.pptx Exception Handling and Multithreading
PPTX
Chap2 exception handling
PPTX
Java-Unit 3- Chap2 exception handling
PPTX
Java exception handling
PPTX
UNIT 2.pptx
PPTX
UNIT III 2021R.pptx
PPTX
UNIT III 2021R.pptx
PPTX
java exception.pptx
PPTX
Java -Exception handlingunit-iv
PDF
Java unit3
PPTX
UNIT 2 UNIT 3 OBJECT ORIENTED PROGRAMMING
PPTX
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
PPTX
Java exception handling
PDF
7_exception.pdf
PPT
Exception
PPT
Exception
PPT
Exception
Unit II Java & J2EE regarding Java application development
JAVA UNIT 2
UNIT-3.pptx Exception Handling and Multithreading
Chap2 exception handling
Java-Unit 3- Chap2 exception handling
Java exception handling
UNIT 2.pptx
UNIT III 2021R.pptx
UNIT III 2021R.pptx
java exception.pptx
Java -Exception handlingunit-iv
Java unit3
UNIT 2 UNIT 3 OBJECT ORIENTED PROGRAMMING
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Java exception handling
7_exception.pdf
Exception
Exception
Exception
Ad

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

PDF
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
PDF
JAVA PROGRAMMING - The Collections Framework
PDF
JAVA PROGRAMMING – Packages - Stream based I/O
PDF
Java programming -Object-Oriented Thinking- Inheritance
PDF
Compiler Design- Machine Independent Optimizations
PDF
PDF
COMPILER DESIGN- Syntax Directed Translation
PDF
COMPILER DESIGN- Introduction & Lexical Analysis:
PPTX
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
PDF
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
PDF
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
PDF
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
PDF
Computer Forensics Working with Windows and DOS Systems
JAVA PROGRAMMING- GUI Programming with Swing - The Swing Buttons
JAVA PROGRAMMING - The Collections Framework
JAVA PROGRAMMING – Packages - Stream based I/O
Java programming -Object-Oriented Thinking- Inheritance
Compiler Design- Machine Independent Optimizations
COMPILER DESIGN- Syntax Directed Translation
COMPILER DESIGN- Introduction & Lexical Analysis:
CRYPTOGRAPHY AND NETWORK SECURITY- E-Mail Security
CRYPTOGRAPHY AND NETWORK SECURITY- Transport-level Security
CRYPTOGRAPHY & NETWORK SECURITY- Cryptographic Hash Functions
CRYPTOGRAPHY & NETWOK SECURITY- Symmetric key Ciphers
Computer Forensics Working with Windows and DOS Systems

Recently uploaded (20)

DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Modernizing your data center with Dell and AMD
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation theory and applications.pdf
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
Big Data Technologies - Introduction.pptx
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
The AUB Centre for AI in Media Proposal.docx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
NewMind AI Monthly Chronicles - July 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Modernizing your data center with Dell and AMD
Dropbox Q2 2025 Financial Results & Investor Presentation
Advanced methodologies resolving dimensionality complications for autism neur...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Unlocking AI with Model Context Protocol (MCP)
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation theory and applications.pdf
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Big Data Technologies - Introduction.pptx
Network Security Unit 5.pdf for BCA BBA.
Reach Out and Touch Someone: Haptics and Empathic Computing
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Mobile App Security Testing_ A Comprehensive Guide.pdf
NewMind AI Weekly Chronicles - August'25 Week I
“AI and Expert System Decision Support & Business Intelligence Systems”

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.