SlideShare a Scribd company logo
Unit 4 exceptions and threads
 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.
Unit 4 exceptions and threads
 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.
Unit 4 exceptions and threads
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

PPTX
Software testing.ppt
PPTX
Introduction to java
PDF
PPTX
Multithreading in java
PPTX
Introduction to java
PDF
Command line-arguments-in-java-tutorial
PPSX
JDBC: java DataBase connectivity
PPT
Manual testing ppt
Software testing.ppt
Introduction to java
Multithreading in java
Introduction to java
Command line-arguments-in-java-tutorial
JDBC: java DataBase connectivity
Manual testing ppt

What's hot (20)

PPT
Exception Handling in JAVA
PPT
Command line arguments.21
PPTX
Introduction to java
PDF
Java threads
PPTX
Basics of JAVA programming
PDF
JAVA PROGRAMMING- Exception handling - Multithreading
PPT
Exception handling
PDF
Introduction to Java Programming
PPTX
Android architecture
PPTX
Introduction to Basic Java Versions and their features
PPTX
Introduction to Software Engineering
PPT
Eclipse introduction IDE PRESENTATION
PPTX
Multithreading in java
PDF
Java Programming
PPTX
Control Statements in Java
PDF
STLC (Software Testing Life Cycle)
PPTX
Introduction to spring boot
PPT
Applet life cycle
PDF
A seminar report on core java
PPT
Exception handling
Exception Handling in JAVA
Command line arguments.21
Introduction to java
Java threads
Basics of JAVA programming
JAVA PROGRAMMING- Exception handling - Multithreading
Exception handling
Introduction to Java Programming
Android architecture
Introduction to Basic Java Versions and their features
Introduction to Software Engineering
Eclipse introduction IDE PRESENTATION
Multithreading in java
Java Programming
Control Statements in Java
STLC (Software Testing Life Cycle)
Introduction to spring boot
Applet life cycle
A seminar report on core java
Exception handling
Ad

Similar to Unit 4 exceptions and threads (20)

PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
PDF
Java unit3
PPTX
Exception handling in Java
PPTX
Interface andexceptions
PPTX
presentation-on-exception-handling 1.pptx
PPTX
presentation-on-exception-handling-160611180456 (1).pptx
PPT
9781439035665 ppt ch11
PDF
Java exceptions
PPTX
Exception Handling.pptx
PPTX
Exception handling in java.pptx
PPT
Chap12
PPT
Exceptionhandling
PPT
8.Exception handling latest(MB).ppt .
DOCX
Exception handling in java
PPTX
Exceptions handling in java
PPTX
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PPTX
UNIT 2.pptx
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPTX
Exception‐Handling in object oriented programming
PPTX
Exception handling in java
Exception Handling,finally,catch,throw,throws,try.pptx
Java unit3
Exception handling in Java
Interface andexceptions
presentation-on-exception-handling 1.pptx
presentation-on-exception-handling-160611180456 (1).pptx
9781439035665 ppt ch11
Java exceptions
Exception Handling.pptx
Exception handling in java.pptx
Chap12
Exceptionhandling
8.Exception handling latest(MB).ppt .
Exception handling in java
Exceptions handling in java
PACKAGES, INTERFACES AND EXCEPTION HANDLING
UNIT 2.pptx
unit 4 msbte syallbus for sem 4 2024-2025
Exception‐Handling in object oriented programming
Exception handling in java
Ad

More from DevaKumari Vijay (20)

PPTX
Unit 1 computer architecture (1)
PPTX
PPTX
PPTX
PPTX
Unit 2 monte carlo simulation
PPTX
Decisiontree&amp;game theory
PPTX
Unit2 network optimization
PPTX
Unit 4 simulation and queing theory(m/m/1)
PPTX
Unit4 systemdynamics
PPTX
Unit 3 des
PPTX
Unit 1 introduction to simulation
PPTX
Unit2 montecarlosimulation
PPT
Unit 3-Greedy Method
PPTX
Unit 5 java-awt (1)
PPTX
Unit3 part3-packages and interfaces
PPTX
Unit3 part2-inheritance
PPTX
Unit3 part1-class
PPTX
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
PPTX
Unit1 introduction to Java
PPT
Introduction to design and analysis of algorithm
Unit 1 computer architecture (1)
Unit 2 monte carlo simulation
Decisiontree&amp;game theory
Unit2 network optimization
Unit 4 simulation and queing theory(m/m/1)
Unit4 systemdynamics
Unit 3 des
Unit 1 introduction to simulation
Unit2 montecarlosimulation
Unit 3-Greedy Method
Unit 5 java-awt (1)
Unit3 part3-packages and interfaces
Unit3 part2-inheritance
Unit3 part1-class
Unit 2-data types,Variables,Operators,Conitionals,loops and arrays
Unit1 introduction to Java
Introduction to design and analysis of algorithm

Recently uploaded (20)

PDF
VCE English Exam - Section C Student Revision Booklet
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Complications of Minimal Access Surgery at WLH
PPTX
GDM (1) (1).pptx small presentation for students
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharma ospi slides which help in ospi learning
PDF
01-Introduction-to-Information-Management.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Insiders guide to clinical Medicine.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Cell Types and Its function , kingdom of life
PPTX
Lesson notes of climatology university.
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
Cell Structure & Organelles in detailed.
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
VCE English Exam - Section C Student Revision Booklet
2.FourierTransform-ShortQuestionswithAnswers.pdf
Complications of Minimal Access Surgery at WLH
GDM (1) (1).pptx small presentation for students
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharma ospi slides which help in ospi learning
01-Introduction-to-Information-Management.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Insiders guide to clinical Medicine.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Cell Types and Its function , kingdom of life
Lesson notes of climatology university.
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Cell Structure & Organelles in detailed.
PPH.pptx obstetrics and gynecology in nursing
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Microbial diseases, their pathogenesis and prophylaxis
O5-L3 Freight Transport Ops (International) V1.pdf

Unit 4 exceptions and threads

  • 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.
  • 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.
  • 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.