SlideShare una empresa de Scribd logo
1 de 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.

Más contenido relacionado

La actualidad más candente

Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
Benj Del Mundo
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 

La actualidad más candente (20)

Exception handling
Exception handlingException handling
Exception handling
 
Java Data Types and Variables
Java Data Types and VariablesJava Data Types and Variables
Java Data Types and Variables
 
JVM
JVMJVM
JVM
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Java exception
Java exception Java exception
Java exception
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java variable types
Java variable typesJava variable types
Java variable types
 
Variable and constants in Vb.NET
Variable and constants in Vb.NETVariable and constants in Vb.NET
Variable and constants in Vb.NET
 
java token
java tokenjava token
java token
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)String Builder & String Buffer (Java Programming)
String Builder & String Buffer (Java Programming)
 
Polymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh SarkarPolymorphism in Java by Animesh Sarkar
Polymorphism in Java by Animesh Sarkar
 
Java program structure
Java program structureJava program structure
Java program structure
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

Similar a Unit 4 exceptions and threads

9781439035665 ppt ch11
9781439035665 ppt ch119781439035665 ppt ch11
9781439035665 ppt ch11
Terry Yoast
 

Similar a Unit 4 exceptions and threads (20)

Java unit3
Java unit3Java unit3
Java unit3
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
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
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
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 in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 

Más de DevaKumari Vijay

Más de 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
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 

Último (20)

TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 

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.