SlideShare a Scribd company logo
1 of 41
 An exception (or exceptional event) is a problem that
arises during the execution of a program.
 When an Exception occurs the normal flow of the
program is disrupted and the program/Application
terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
 An exception can occur for many different reasons.
 A user has entered an invalid data.
 A file that needs to be opened cannot be found.
 A network connection has been lost in the middle of
communications or the JVM has run out of memory.
 Checked exceptions − A checked exception is an exception
that is checked (notified) by the compiler at compilation-
time, these are also called as compile time exceptions. These
exceptions cannot simply be ignored, the programmer
should take care of () these exceptions. Eg:
FileNotFoundException
 Unchecked exceptions − An unchecked exception is an
exception that occurs at the time of execution. These are also
called as Runtime Exceptions. These include programming
bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Eg: ArrayIndexOutOfBoundsExceptionexception
 Errors − These are not exceptions at all, but problems that
arise beyond the control of the user or the programmer.
Errors are typically ignored in your code because you can
rarely do anything about an error. For example, if a stack
overflow occurs, an error will arise. They are also ignored at
the time of compilation.
 Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally.
 A try/catch block is placed around the code that might
generate an exception. Code within a try/catch block is
referred to as protected code.
 Syntax
try{
//code that may throw an exception
}catch(Exception_class_Name ref)
{
}
 The code which is prone to exceptions is placed in the
try block.
 When an exception occurs, that exception occurred is
handled by catch block associated with it.
 Every try block should be immediately followed either
by a catch block or finally block.
 A catch statement involves declaring the type
of exception you are trying to catch.
 If an exception occurs in protected code, the
catch block (or blocks) that follows the try is
checked.
 If the type of exception that occurred is listed in
a catch block, the exception is passed to the
catch block much as an argument is passed into
a method parameter.
import java.io.*;
public class ExcepTest {
public static void main(String args[]) {
try {
int a[] = new int[2];
System.out.println("Access element three :" +
a[3]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown :" + e);
}
System.out.println("Out of the block");
}
}
try The "try" keyword is used to specify a block where
exception code should be placed. The try block must be
followed by either catch or finally. It means, we can't use
try block alone.
catch The "catch" block is used to handle the exception. It must
be preceded by try block ,i.e catch block alone cannot be
used. It can be followed by finally block later.
finally The "finally" block is used to execute the important code
of the program. It is executed whether an exception is
handled or not.
throw The "throw" keyword is used to throw an exception.
throws The "throws" keyword is used to declare exceptions. It
doesn't throw an exception. It specifies that there may
occur an exception in the method. It is always used with
method signature.
public class TryCatchExample2 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
// if exception occurs, the remaining statement will not exceute
System.out.println("rest of the code");
}
// handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
}
}
try {
// Protected code
} catch (ExceptionType1 e1) {
// Catch block
} catch (ExceptionType2 e2) {
// Catch block
} catch (ExceptionType3 e3) {
// Catch block
}
 A try block can be followed by one or more
catch blocks. Each catch block must contain a
different exception handler.
 At a time only one exception occurs and at a
time only one catch block is executed.
 All catch blocks must be ordered from most
specific to most general, i.e. catch for
ArithmeticException must come before catch
for Exception.
public class MultipleCatchBlock1 {
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
public class MultipleCatchBlock2
public static void main(String[] args) {
try{
int a[]=new int[5];
a[5]=30/0;
System.out.println(a[10]);
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
o/p: Arithmetic Exception occurs
public class MultipleCatchBlock3{
public static void main(String[] args) {
try{
Int a=25/0;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
 Arithmetic exception is generate d, but the corresponding exception type
is not provided. In such case, the catch block containing the parent
exception class Exception will invoked.
 In a method, there can be more than one statements that might
throw exception, So put all these statements within its own try
block and provide separate exception handler within own catch
block for each of them.
 If an exception occurs within the try block, that exception is
handled by the exception handler associated with it. To associate
exception handler, we must put catch block after it.
 There can be more than one exception handlers. Each catch block
is a exception handler that handles the exception of the type
indicated by its argument. The argument, ExceptionType declares
the type of the exception that it can handle and must be the name
of the class that inherits from Throwable class.
 For each try block there can be zero or more catch blocks, but only
one finally block.
 The finally block is optional.It always gets executed whether an
exception occurred in try block or not .
 If exception occurs, then it will be executed after try and catch
blocks. And if exception does not occur then it will be executed
after the try block.
 The finally block in java is used to put important codes such as
clean up code e.g. closing the file or closing the connection.
The try block within a try block is known as nested try block in java.
Syntax:
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
class NestedException1{
public static void main(String args[]){
try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}
try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e)
{System.out.println(e);}
System.out.println("other statement);
}catch(Exception e){System.out.println("handeled");}
System.out.println("normal flow..");
}
}
class NestedException2 {
public static void main(String args[])
{
try {
try {
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}
// handles ArithmeticException if any
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" try-block2");
}
}
// handles ArrayIndexOutOfBoundsException if any
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print("ArrayIndexOutOfBoundsException");
System.out.println(" main try-block");
}
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
 Java finally block is a block that is used to
execute important code such as closing
connection, stream etc.
 Java finally block is always executed whether
exception is handled or not.
 Java finally block follows try or catch block.
Example where exception doesn't occur.
class FinallyBlockTest 1{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Exception occurs and not handled.
class FinallyBlockTest2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
Exception occurs and handled.
public class FinallyBlockTest3{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{System.out.println(e);}
finally
{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
 Definition: Throw is a keyword which is used to throw an
exception explicitly in the program inside a function or
inside a block of code.
 Internal implementation : Internally throw is implemented
as it is allowed to throw only single exception at a time i.e
we cannot throw multiple exception with throw keyword.
 Type of exception: With throw keyword we can propagate
only unchecked exception i.e checked exception cannot be
propagated using throw.
 Syntax: Syntax wise throw keyword is followed by the
instance variable.
 Declaration: throw keyword is used within the method. void
m(){
throw new ArithmeticException("sorry");
}
public class ThrowTest{
public void checkAge(int age){
if(age<18)
throw new ArithmeticException("Not Eligible
for voting");
else
System.out.println("Eligible for voting");
}
public static void main(String args[]){
ThrowTest obj = new ThrowTest();
obj.checkAge(13);
System.out.println("End Of Program");
}
}
 Definition: Throws is a keyword used in the method
signature used to declare an exception which might get
thrown by the function while executing the code.
 Internal implementation: can declare multiple
exceptions with throws keyword that could get thrown
by the function where throws keyword is used.
 Type of exception: with throws keyword both checked
and unchecked exceptions can be declared keyword
followed by specific exception class name.
 Syntax : throws keyword is followed by exception
class names.
 Declaration : throws keyword is used with the method
signature.
void m()throws ArithmeticException{
//method code
}
public class ThrowsTest{
public int division(int a, int b) throws
ArithmeticException,IOException{
int t = a/b;
return t;
}
public static void main(String args[]){
JavaTester obj = new JavaTester();
try{
System.out.println(obj.division(15,0));
}
catch(ArithmeticException e){
System.out.println("You shouldn't divide number by
zero");
}
}
}
throw throws
Java throw keyword is used to
explicitly throw an exception.
Java throws keyword is used to
declare an exception that might
occur.
Checked exception cannot be
propagated using throw only. It is
useful specially with custom
exceptions.
Checked exception can be
propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method or
block.
Throws is used with the method
signature.
Exception object is manually
thrown by programmer, it is handled
by JVM
Exception specified using throws is
taken care by the caller method.
You cannot throw multiple
exceptions.
You can declare multiple exceptions
e.g.
public void method()throws
IOException,SQLException.
 Java custom exceptions or user defined
exceptions are used to customize the exception
according to user need.
 User can create their own exception class and
throws that exception using ‘throw’ keyword.
 custom exceptions are created by extending the
class Exception.
class InvalidAgeException extends RuntimeException{
InvalidAgeException(String s){
super(s);
}
}
class CustomExceptionTest1{
static void validate(int age) {
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
validate(13);
System.out.println("rest of the code...");
}
}
 Built-in exceptions are the exceptions which are available in Java
libraries.
 Following are examples of unchecked exceptions
Sr.N
o.
Exception & Description
1 ArithmeticException
Arithmetic error, such as divide-by-zero.
2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.
3 ArrayStoreException
Assignment to an array element of an incompatible
type.
4 NegativeArraySizeException
Array created with a negative size.
5 NullPointerException
Invalid use of a null reference.
6 NumberFormatException
Invalid conversion of a string to a numeric format.
7 SecurityException
Attempt to violate security.
8 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
9 UnsupportedOperationException
An unsupported operation was encountered.
Sr.No. Exception & Description
1 ClassNotFoundException
Class not found.
2 IllegalAccessException
Access to a class is denied.
3 InstantiationException
Attempt to create an object of an abstract class or interface.
4 InterruptedException
One thread has been interrupted by another thread.
5 NoSuchFieldException
A requested field does not exist.
6 NoSuchMethodException
A requested method does not exist.
 A multi-threaded program contains two or more parts that can
run concurrently and each part can handle a different task at the
same time making optimal use of the available resources.
 Multi threading subdivides specific operations within a single
application into individual threads.
 Each of the threads can run in parallel.
 The OS divides processing time not only among different
applications, but also among each thread within an application.
 Multi-threading enables you to write in a way where multiple
activities can proceed concurrently in the same program.
Multithreading in Java is a process of executing multiple threads
simultaneously.
 A thread is a lightweight sub-process, the smallest unit of
processing. Multiprocessing and multithreading, both are used to
achieve multitasking.
 However, we use multithreading than multiprocessing because
threads use a shared memory area. They don't allocate separate
memory area so saves memory.
 Thread is 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 uses a
shared memory area.
 A thread goes through various stages in its life cycle.
For example, a thread is born, started, runs, and then
dies. The following diagram shows the complete life
cycle of a thread.
 Every Java thread has a priority that helps the
operating system determine the order in which
threads are scheduled.
 Java thread priorities are in the range between
MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default,
every thread is given priority NORM_PRIORITY
(a constant of 5).
 Threads with higher priority are more important to
a program and should be allocated processor time
before lower-priority threads. However, thread
priorities cannot guarantee the order in which
threads execute and are very much platform
dependent.
 Thread creation in Java;
 Thread implementation in java can be achieved in two ways:
 Extending the java.lang.Thread class
 Implementing the java.lang.Runnable Interface
 Note: The Thread and Runnable are available in the
java.lang.* package
 1) By extending thread class
 The class should extend Java Thread class.
 The class should override the run() method.
 The functionality that is expected by the Thread to be
executed is written in the run() method.
 void start(): Creates a new thread and makes it runnable.
 void run(): The new thread begins its life inside this method.
public class ThreadTest1 extends Thread {
public void run(){
System.out.println("thread is running...");
}
public static void main(String[] args) {
ThreadTest1 obj = new ThreadTest1();
obj.start();
}
By Implementing Runnable interface
 The class should implement the Runnable interface
 The class should implement the run() method in
the Runnable interface
 The functionality that is expected by the Thread to
be executed is put in the run() method
public class ThreadTest2 implements Runnable {
public void run(){
System.out.println("thread is running..");
}
public static void main(String[] args) {
Thread t = new Thread(new ThreadTest2());
t.start();
}
 Ending Thread:
 A Thread ends due to the following reasons:
 The thread ends when it comes when the run()
method finishes its execution.
 When the thread throws an Exception or Error
that is not being caught in the program.
 Java program completes or ends.
 Another thread calls stop() methods.

More Related Content

What's hot

What's hot (20)

L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Java packages
Java packagesJava packages
Java packages
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
 
JRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVAJRE , JDK and platform independent nature of JAVA
JRE , JDK and platform independent nature of JAVA
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception Handling in C#
Exception Handling in C#Exception Handling in C#
Exception Handling in C#
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 

Similar to Unit 4 exceptions and threads

Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11Terry Yoast
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 

Similar to Unit 4 exceptions and threads (20)

Java unit3
Java unit3Java unit3
Java unit3
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Chap12
Chap12Chap12
Chap12
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 

More from DevaKumari Vijay

More from DevaKumari Vijay (20)

Unit 1 computer architecture (1)
Unit 1   computer architecture (1)Unit 1   computer architecture (1)
Unit 1 computer architecture (1)
 
Os ch1
Os ch1Os ch1
Os ch1
 
Unit2
Unit2Unit2
Unit2
 
Unit 1
Unit 1Unit 1
Unit 1
 
Unit 2 monte carlo simulation
Unit 2 monte carlo simulationUnit 2 monte carlo simulation
Unit 2 monte carlo simulation
 
Decisiontree&amp;game theory
Decisiontree&amp;game theoryDecisiontree&amp;game theory
Decisiontree&amp;game theory
 
Unit2 network optimization
Unit2 network optimizationUnit2 network optimization
Unit2 network optimization
 
Unit 4 simulation and queing theory(m/m/1)
Unit 4  simulation and queing theory(m/m/1)Unit 4  simulation and queing theory(m/m/1)
Unit 4 simulation and queing theory(m/m/1)
 
Unit4 systemdynamics
Unit4 systemdynamicsUnit4 systemdynamics
Unit4 systemdynamics
 
Unit 3 des
Unit 3 desUnit 3 des
Unit 3 des
 
Unit 1 introduction to simulation
Unit 1 introduction to simulationUnit 1 introduction to simulation
Unit 1 introduction to simulation
 
Unit2 montecarlosimulation
Unit2 montecarlosimulationUnit2 montecarlosimulation
Unit2 montecarlosimulation
 
Unit 3-Greedy Method
Unit 3-Greedy MethodUnit 3-Greedy Method
Unit 3-Greedy Method
 
Unit 5 java-awt (1)
Unit 5 java-awt (1)Unit 5 java-awt (1)
Unit 5 java-awt (1)
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Unit3 part2-inheritance
Unit3 part2-inheritanceUnit3 part2-inheritance
Unit3 part2-inheritance
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arraysUnit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to design and analysis of algorithm
Introduction to design and analysis of algorithmIntroduction to design and analysis of algorithm
Introduction to design and analysis of algorithm
 

Recently uploaded

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Unit 4 exceptions and threads

  • 1.
  • 2.  An exception (or exceptional event) is a problem that arises during the execution of a program.  When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore, these exceptions are to be handled.  An exception can occur for many different reasons.  A user has entered an invalid data.  A file that needs to be opened cannot be found.  A network connection has been lost in the middle of communications or the JVM has run out of memory.
  • 3.  Checked exceptions − A checked exception is an exception that is checked (notified) by the compiler at compilation- time, these are also called as compile time exceptions. These exceptions cannot simply be ignored, the programmer should take care of () these exceptions. Eg: FileNotFoundException  Unchecked exceptions − An unchecked exception is an exception that occurs at the time of execution. These are also called as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API. Runtime exceptions are ignored at the time of compilation. Eg: ArrayIndexOutOfBoundsExceptionexception  Errors − These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
  • 4.
  • 5.  Java exception handling is managed via five keywords: try, catch, throw, throws, and finally.  A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code.  Syntax try{ //code that may throw an exception }catch(Exception_class_Name ref) { }  The code which is prone to exceptions is placed in the try block.  When an exception occurs, that exception occurred is handled by catch block associated with it.  Every try block should be immediately followed either by a catch block or finally block.
  • 6.  A catch statement involves declaring the type of exception you are trying to catch.  If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked.  If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
  • 7. import java.io.*; public class ExcepTest { public static void main(String args[]) { try { int a[] = new int[2]; System.out.println("Access element three :" + a[3]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } }
  • 8. try The "try" keyword is used to specify a block where exception code should be placed. The try block must be followed by either catch or finally. It means, we can't use try block alone. catch The "catch" block is used to handle the exception. It must be preceded by try block ,i.e catch block alone cannot be used. It can be followed by finally block later. finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. throw The "throw" keyword is used to throw an exception. throws The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature.
  • 9. public class TryCatchExample2 { public static void main(String[] args) { try { int data=50/0; //may throw exception // if exception occurs, the remaining statement will not exceute System.out.println("rest of the code"); } // handling the exception catch(ArithmeticException e) { System.out.println(e); } } }
  • 10. try { // Protected code } catch (ExceptionType1 e1) { // Catch block } catch (ExceptionType2 e2) { // Catch block } catch (ExceptionType3 e3) { // Catch block }
  • 11.  A try block can be followed by one or more catch blocks. Each catch block must contain a different exception handler.  At a time only one exception occurs and at a time only one catch block is executed.  All catch blocks must be ordered from most specific to most general, i.e. catch for ArithmeticException must come before catch for Exception.
  • 12. public class MultipleCatchBlock1 { public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }
  • 13. public class MultipleCatchBlock2 public static void main(String[] args) { try{ int a[]=new int[5]; a[5]=30/0; System.out.println(a[10]); } catch(ArithmeticException e) { System.out.println("Arithmetic Exception occurs"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } } o/p: Arithmetic Exception occurs
  • 14. public class MultipleCatchBlock3{ public static void main(String[] args) { try{ Int a=25/0; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("ArrayIndexOutOfBounds Exception occurs"); } catch(Exception e) { System.out.println("Parent Exception occurs"); } System.out.println("rest of the code"); } }  Arithmetic exception is generate d, but the corresponding exception type is not provided. In such case, the catch block containing the parent exception class Exception will invoked.
  • 15.  In a method, there can be more than one statements that might throw exception, So put all these statements within its own try block and provide separate exception handler within own catch block for each of them.  If an exception occurs within the try block, that exception is handled by the exception handler associated with it. To associate exception handler, we must put catch block after it.  There can be more than one exception handlers. Each catch block is a exception handler that handles the exception of the type indicated by its argument. The argument, ExceptionType declares the type of the exception that it can handle and must be the name of the class that inherits from Throwable class.  For each try block there can be zero or more catch blocks, but only one finally block.  The finally block is optional.It always gets executed whether an exception occurred in try block or not .  If exception occurs, then it will be executed after try and catch blocks. And if exception does not occur then it will be executed after the try block.  The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection.
  • 16. The try block within a try block is known as nested try block in java. Syntax: try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } } catch(Exception e) { }
  • 17. class NestedException1{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsException e) {System.out.println(e);} System.out.println("other statement); }catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } }
  • 18. class NestedException2 { public static void main(String args[]) { try { try { try { int arr[] = { 1, 2, 3, 4 }; System.out.println(arr[10]); } // handles ArithmeticException if any catch (ArithmeticException e) { System.out.println("Arithmetic exception"); System.out.println(" try-block2"); } } // handles ArrayIndexOutOfBoundsException if any catch (ArrayIndexOutOfBoundsException e4) { System.out.print("ArrayIndexOutOfBoundsException"); System.out.println(" main try-block"); } } catch (Exception e5) { System.out.print("Exception"); System.out.println(" handled in main try-block"); } } }
  • 19.  Java finally block is a block that is used to execute important code such as closing connection, stream etc.  Java finally block is always executed whether exception is handled or not.  Java finally block follows try or catch block.
  • 20.
  • 21. Example where exception doesn't occur. class FinallyBlockTest 1{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e) {System.out.println(e);} finally {System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } }
  • 22. Exception occurs and not handled. class FinallyBlockTest2{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(NullPointerException e) {System.out.println(e);} finally {System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } }
  • 23. Exception occurs and handled. public class FinallyBlockTest3{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e) {System.out.println(e);} finally {System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } }
  • 24.  Definition: Throw is a keyword which is used to throw an exception explicitly in the program inside a function or inside a block of code.  Internal implementation : Internally throw is implemented as it is allowed to throw only single exception at a time i.e we cannot throw multiple exception with throw keyword.  Type of exception: With throw keyword we can propagate only unchecked exception i.e checked exception cannot be propagated using throw.  Syntax: Syntax wise throw keyword is followed by the instance variable.  Declaration: throw keyword is used within the method. void m(){ throw new ArithmeticException("sorry"); }
  • 25. public class ThrowTest{ public void checkAge(int age){ if(age<18) throw new ArithmeticException("Not Eligible for voting"); else System.out.println("Eligible for voting"); } public static void main(String args[]){ ThrowTest obj = new ThrowTest(); obj.checkAge(13); System.out.println("End Of Program"); } }
  • 26.  Definition: Throws is a keyword used in the method signature used to declare an exception which might get thrown by the function while executing the code.  Internal implementation: can declare multiple exceptions with throws keyword that could get thrown by the function where throws keyword is used.  Type of exception: with throws keyword both checked and unchecked exceptions can be declared keyword followed by specific exception class name.  Syntax : throws keyword is followed by exception class names.  Declaration : throws keyword is used with the method signature. void m()throws ArithmeticException{ //method code }
  • 27. public class ThrowsTest{ public int division(int a, int b) throws ArithmeticException,IOException{ int t = a/b; return t; } public static void main(String args[]){ JavaTester obj = new JavaTester(); try{ System.out.println(obj.division(15,0)); } catch(ArithmeticException e){ System.out.println("You shouldn't divide number by zero"); } } }
  • 28. throw throws Java throw keyword is used to explicitly throw an exception. Java throws keyword is used to declare an exception that might occur. Checked exception cannot be propagated using throw only. It is useful specially with custom exceptions. Checked exception can be propagated with throws. Throw is followed by an instance. Throws is followed by class. Throw is used within the method or block. Throws is used with the method signature. Exception object is manually thrown by programmer, it is handled by JVM Exception specified using throws is taken care by the caller method. You cannot throw multiple exceptions. You can declare multiple exceptions e.g. public void method()throws IOException,SQLException.
  • 29.  Java custom exceptions or user defined exceptions are used to customize the exception according to user need.  User can create their own exception class and throws that exception using ‘throw’ keyword.  custom exceptions are created by extending the class Exception.
  • 30. class InvalidAgeException extends RuntimeException{ InvalidAgeException(String s){ super(s); } } class CustomExceptionTest1{ static void validate(int age) { if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ validate(13); System.out.println("rest of the code..."); } }
  • 31.  Built-in exceptions are the exceptions which are available in Java libraries.  Following are examples of unchecked exceptions Sr.N o. Exception & Description 1 ArithmeticException Arithmetic error, such as divide-by-zero. 2 ArrayIndexOutOfBoundsException Array index is out-of-bounds. 3 ArrayStoreException Assignment to an array element of an incompatible type.
  • 32. 4 NegativeArraySizeException Array created with a negative size. 5 NullPointerException Invalid use of a null reference. 6 NumberFormatException Invalid conversion of a string to a numeric format. 7 SecurityException Attempt to violate security. 8 StringIndexOutOfBounds Attempt to index outside the bounds of a string. 9 UnsupportedOperationException An unsupported operation was encountered.
  • 33. Sr.No. Exception & Description 1 ClassNotFoundException Class not found. 2 IllegalAccessException Access to a class is denied. 3 InstantiationException Attempt to create an object of an abstract class or interface. 4 InterruptedException One thread has been interrupted by another thread. 5 NoSuchFieldException A requested field does not exist. 6 NoSuchMethodException A requested method does not exist.
  • 34.  A multi-threaded program contains two or more parts that can run concurrently and each part can handle a different task at the same time making optimal use of the available resources.  Multi threading subdivides specific operations within a single application into individual threads.  Each of the threads can run in parallel.  The OS divides processing time not only among different applications, but also among each thread within an application.  Multi-threading enables you to write in a way where multiple activities can proceed concurrently in the same program. Multithreading in Java is a process of executing multiple threads simultaneously.  A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.  However, we use multithreading than multiprocessing because threads use a shared memory area. They don't allocate separate memory area so saves memory.
  • 35.  Thread is 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 uses a shared memory area.
  • 36.  A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, and then dies. The following diagram shows the complete life cycle of a thread.
  • 37.  Every Java thread has a priority that helps the operating system determine the order in which threads are scheduled.  Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).  Threads with higher priority are more important to a program and should be allocated processor time before lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and are very much platform dependent.
  • 38.  Thread creation in Java;  Thread implementation in java can be achieved in two ways:  Extending the java.lang.Thread class  Implementing the java.lang.Runnable Interface  Note: The Thread and Runnable are available in the java.lang.* package  1) By extending thread class  The class should extend Java Thread class.  The class should override the run() method.  The functionality that is expected by the Thread to be executed is written in the run() method.  void start(): Creates a new thread and makes it runnable.  void run(): The new thread begins its life inside this method.
  • 39. public class ThreadTest1 extends Thread { public void run(){ System.out.println("thread is running..."); } public static void main(String[] args) { ThreadTest1 obj = new ThreadTest1(); obj.start(); }
  • 40. By Implementing Runnable interface  The class should implement the Runnable interface  The class should implement the run() method in the Runnable interface  The functionality that is expected by the Thread to be executed is put in the run() method public class ThreadTest2 implements Runnable { public void run(){ System.out.println("thread is running.."); } public static void main(String[] args) { Thread t = new Thread(new ThreadTest2()); t.start(); }
  • 41.  Ending Thread:  A Thread ends due to the following reasons:  The thread ends when it comes when the run() method finishes its execution.  When the thread throws an Exception or Error that is not being caught in the program.  Java program completes or ends.  Another thread calls stop() methods.