SlideShare a Scribd company logo
Unit - III
Exception Handling and Multithreading
What is Exception in Java?
 Exceptions are events that occur during the execution of programs that disrupt the
normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).
 Exception is an object which is thrown at runtime.
 Exception objects can be thrown and caught.
What is Exception Handling?
 Exception Handling is a mechanism to handle runtime errors such as
 ClassNotFoundException,
 IOException,
 SQLException,
 RemoteException, etc.
Advantage of Exception Handling
 The advantage of exception handling is to maintain the normal flow of the
application.
 An exception normally disrupts the normal flow of the application; that is why we
need to handle exceptions.
 Example:
statement 1;
statement 2;
statement 3;
statement 4;
statement 5;//exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
 Suppose there are 10 statements in a Java program and an exception occurs at
statement 5;
 The rest of the code will not be executed, i.e., statements 6 to 10 will not be
executed.
 However, when we perform exception handling, the rest of the statements will be
executed. That is why we use exception handling in Java.
Hierarchy of Java Exception classes
 The java.lang.Throwable class is the root class of Java Exception.
 The hierarchy inherited by two subclasses:
 Exception and
 Error
Exceptions are used to indicate many different types of error conditions.
 JVM Errors:
 OutOfMemoryError
 StackOverflowError
 LinkageError
 System errors:
 FileNotFoundException
 IOException
 SocketTimeoutException
 Programming errors:
 NullPointerException
 ArrayIndexOutOfBoundsException
 ArithmeticException
Types of Exceptions
 Java defines several types of exceptions that relate to its various class libraries.
 Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
 Checked Exception
 Unchecked Exception
2. User-Defined Exceptions
1. Built-in Exceptions
 Built-in exceptions are the exceptions that are available in Java libraries.
 These exceptions are suitable to explain certain error situations.
Checked Exceptions: Checked exceptions are called compile-time exceptions
because these exceptions are checked at compile-time by the compiler.
Unchecked Exceptions: The compiler will not check these exceptions at compile
time. In simple words, if a program throws an unchecked exception, and even if we
didn’t handle or declare it, the program would not give a compilation error.
2. User-Defined Exceptions:
 Users can also create exceptions, which are called ‘user-defined Exceptions’.
Advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types
Common Scenarios of Java Exceptions
 There are given some scenarios where unchecked exceptions may occur. They are
as follows:
1) A scenario where ArithmeticException occurs
 If we divide any number by zero, there occurs an ArithmeticException.
int a=50/0; //ArithmeticException
2) A scenario where NullPointerException occurs
 If we have a null value in any variable, performing any operation on the variable
throws a NullPointerException.
String s=null;
System.out.println(s.length()); //NullPointerException
3) A scenario where NumberFormatException occurs
 If the formatting of any variable or number is mismatched, it may result into
NumberFormatException.
 Suppose we have a string variable that has characters; converting this variable into
digit will cause NumberFormatException.
String s="abc";
int i=Integer.parseInt(s); //NumberFormatException
4) A scenario where ArrayIndexOutOfBoundsException occurs
 When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.
 There may be other reasons to occur ArrayIndexOutOfBoundsException.
int a[]=new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
Java Exception Keywords
 Java provides five keywords that are used to handle the exception.
Keyword Description
Try  The "try" keyword is used to specify a block where we
should place an exception code.
 It means we can't use try block alone.
 The try block must be followed by either catch or finally.
Catch  The "catch" block is used to handle the exception.
 It must be preceded by try block which means we can't use
catch block alone.
Finally  The "finally" block is used to execute the necessary 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 specifies that there may occur an exception in the method.
 It doesn't throw an exception.
 It is always used with method signature.
Java try and catch
 The try statement allows you to define a block of code to be tested for errors while
it is being executed.
 The catch statement allows you to define a block of code to be executed, if an error
occurs in the try block.
Java try block:
 Java try block is used to enclose the code that might throw an exception.
 It must be used within the method.
 If an exception occurs at the particular statement in the try block, the rest of the
block code will not execute.
 So, it is recommended not to keep the code in try block that will not throw an
exception.
 Java try block must be followed by either catch or finally block.
Syntax of Java try-catch:
try
{
//code that may throw an exception
}
catch(Exception_class_Name ref)
{
}
Syntax of try-finally block:
Try
{
//code that may throw an exception
}
Finally
{
}
Java catch block
 Java catch block is used to handle the Exception by declaring the type of exception
within the parameter.
 The declared exception must be the parent class exception ( i.e., Exception)
 The catch block must be used after the try block only.
 You can use multiple catch block with a single try block.
Internal Working of Java try-catch block:
 The JVM firstly checks whether the exception is handled or not.
 If exception is not handled, JVM provides a default exception handler that performs
the following tasks:
 Prints out exception description.
 Prints the stack trace (Hierarchy of methods where the exception occurred).
 Causes the program to terminate.
 But if the application programmer handles the exception, the normal flow of the
application is maintained, i.e., rest of the code is executed.
Example1: Problem without exception handling
 if we don't use a try-catch block.
public class TryCatchExample1
{
public static void main(String[] args)
{
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
Example 2: Solution by exception handling
 Using java try-catch block.
public class TryCatchExample2
{
public static void main(String[] args)
{
try
{
int data=50/0; //may throw exception
}
//handling the exception
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 3: In this example, we also kept the code in a try block that will not throw
an exception.
public class TryCatchExample3 {
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);
}
}
}
Output:
java.lang.ArithmeticException: / by zero
Here, we can see that if an exception occurs in the try block, the rest of the block code will
not execute.
Example 4: Here, we handle the exception using the parent class exception.
public class TryCatchExample4 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
System.out.println(e);
}
System.out.println("rest of the code");
}
}
Output:
java.lang.ArithmeticException: / by zero
rest of the code
Example 5: to print a custom message on exception.
public class TryCatchExample5 {
public static void main(String[] args) {
try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
System.out.println("Can't divided by zero");
}
}
}
Output: Can't divided by zero
Example 6: to resolve the exception in a catch block.
public class TryCatchExample6 {
public static void main(String[] args) {
int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
System.out.println(i/(j+2));
}
}
}
Output:
25
Java Multi-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.
Example: java multi-catch block.
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");
}
}
OUTPUT
Arithmetic Exception occurs
rest of the code
Java Nested try block:
 In Java, using a try block inside another try block is permitted. It is called as nested
try block.
 For example, the inner try block can be used to
handle ArrayIndexOutOfBoundsException while the outer try block can handle
the ArithemeticException (division by zero).
Syntax:
....
//main try block
try
{
statement 1;
statement 2;
//try catch block within another try block
try
{
statement 3;
statement 4;
//try catch block within nested try block
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//exception message
}
}
catch(Exception e1)
{
//exception message
}
}
//catch block of parent (outer) try block
catch(Exception e3)
{
//exception message
}
....
Example: a try block within another try block for two different exceptions.
public class NestedTryBlock{
public static void main(String args[]){
//outer try block
try{
//inner try block 1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//catch block of inner try block 1
catch(ArithmeticException e)
{
System.out.println(e);
}
//inner try block 2
try{
int a[]=new int[5];
//assigning the value out of array bounds
a[5]=4;
}
//catch block of inner try block 2
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//catch block of outer try block
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
Output:
Java throw keyword
 The Java throw keyword is used to throw an exception explicitly.
 We can define our own set of conditions and throw an exception explicitly using
throw keyword.
 For example, we can throw ArithmeticException if we divide a number by another
number.
 Here, we just need to set the condition and throw exception using throw keyword.
The syntax of the Java throw keyword is given below.
throw Instance i.e.,
throw new exception_class("error message");
Example of throw IOException.
throw new IOException("sorry device error");
Java throw keyword Example
Example 1: Throwing Unchecked Exception
 In this example, we have created a method named validate() that accepts an integer
as a parameter.
 If the age is less than 18, we are throwing the ArithmeticException otherwise print a
message welcome to vote.
public class TestThrow1 {
//function to check if person is eligible to vote or not
public static void validate(int age) {
if(age<18) {
//throw Arithmetic exception if not eligible to vote
throw new ArithmeticException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[]){
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
Example 2: Throwing Checked Exception
Every subclass of Error and RuntimeException is an unchecked exception in java. A
checked exception is everything else under the Throwable class.
import java.io.*;
public class TestThrow2 {
//function to check if person is eligible to vote or not
public static void method() throws FileNotFoundException {
FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt");
BufferedReader fileInput = new BufferedReader(file);
throw new FileNotFoundException();
}
//main method
public static void main(String args[]){
try
{
method();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
System.out.println("rest of the code...");
}
}
Output:
Example 3: Throwing User-defined Exception
exception is everything else under the Throwable class.
TestThrow3.java
// class represents user-defined exception
class UserDefinedException extends Exception
{
public UserDefinedException(String str)
{
// Calling constructor of parent Exception
super(str);
}
}
// Class that uses above MyException
public class TestThrow3
{
public static void main(String args[])
{
try
{
// throw an object of user defined exception
throw new UserDefinedException("This is user-defined exception");
}
catch (UserDefinedException ude)
{
System.out.println("Caught the exception");
// Print the message from MyException object
System.out.println(ude.getMessage());
}
}
}
Output:
Java finally block
Java finally block is a block used to execute important code such as closing the
connection, etc.
Java finally block is always executed whether an exception is handled or not. Therefore, it
contains all the necessary statements that need to be printed regardless of the exception
occurs or not.
The finally block follows the try-catch block.
Example:
Case 1: When an exception does not occur
 Java program does not throw any exception, and the finally block is executed after
the try block.
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT
Case 2: When an exception occur but not handled by the catch block
 Here, the code throws an exception however the catch block cannot handle it.
 Despite this, the finally block is executed after the try block and then the program
terminates abnormally.
public class TestFinallyBlock1{
public static void main(String args[]){
try {
System.out.println("Inside the try block");
//below code throws divide by zero exception
int data=25/0;
System.out.println(data);
}
//cannot handle Arithmetic type exception
//can only accept Null Pointer type exception
catch(NullPointerException e){
System.out.println(e);
}
//executes regardless of exception occured or not
finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
Lab Program7:Write a java program to implement Exception Handling
import java.io.*;
class MyException extends Exception
{
private int detail;
MyException(int a)
{
detail=a;
}
public String toString()
{
return "Minor with age less than 18 and you are only "+detail;
}
}
class ExceptionDemo
{
static void compute(int x)throws MyException
{
if(x<18)
throw new MyException(x);
else
System.out.println("You can voten");
}
public static void main(String arg[])
{
try
{
compute(20);
compute(15);
}
catch(MyException e)
{
System.out.println("My Exception caught "+e);
}
finally
{
System.out.println("nYou are an Indian");
} } }
Ad

Recommended

Exception Handling.pptx
Exception Handling.pptx
primevideos176
 
Exception handling basic
Exception handling basic
TharuniDiddekunta
 
UNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
VTU MCA 2022 JAVA Exceeption Handling.docx
VTU MCA 2022 JAVA Exceeption Handling.docx
Poornima E.G.
 
Exception handling in java
Exception handling in java
Kavitha713564
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
Assistant Professor, Shri Shivaji Science College, Amravati
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in java
pooja kumari
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Exception Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Exception handling
Exception handling
Ardhendu Nandi
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling in java
Exception handling in java
ARAFAT ISLAM
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Java SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception handling
Exception handling
Garuda Trainings
 
Exception handling
Exception handling
Garuda Trainings
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Introduction to Exception
Introduction to Exception
Swabhav Techlabs
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Data Structures Stack and Queue Data Structures
Data Structures Stack and Queue Data Structures
poongothai11
 
Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.
poongothai11
 

More Related Content

Similar to Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch. (20)

Exception handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in java
pooja kumari
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Exception Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
Exception handling
Exception handling
Ardhendu Nandi
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
JAVA PPT -4 BY ADI.pdf
JAVA PPT -4 BY ADI.pdf
Prof. Dr. K. Adisesha
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling in java
Exception handling in java
ARAFAT ISLAM
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Exceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Java SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Exception handling
Exception handling
Garuda Trainings
 
Exception handling
Exception handling
Garuda Trainings
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Introduction to Exception
Introduction to Exception
Swabhav Techlabs
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Exception handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in java
pooja kumari
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Exception Handling in JAVA
Exception Handling in JAVA
SURIT DATTA
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Exception handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling in java
Exception handling in java
ARAFAT ISLAM
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Java SE 11 Exception Handling
Java SE 11 Exception Handling
Ashwin Shiv
 
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
oop-unit-iii-ppt.pptexceptionhandlingobjectorientedprogramming
ssuserf45a65
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 
Java Exception Handling & IO-Unit-3 (1).ppt
Java Exception Handling & IO-Unit-3 (1).ppt
SahilKumar542
 

More from poongothai11 (10)

Data Structures Stack and Queue Data Structures
Data Structures Stack and Queue Data Structures
poongothai11
 
Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.
poongothai11
 
Introduction to Database Management Systems
Introduction to Database Management Systems
poongothai11
 
Open System Interconnection model and its layers.pdf
Open System Interconnection model and its layers.pdf
poongothai11
 
Computer Organization Introduction, Generations of Computer.pptx
Computer Organization Introduction, Generations of Computer.pptx
poongothai11
 
C Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdf
poongothai11
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
poongothai11
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
poongothai11
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
Data Structures Stack and Queue Data Structures
Data Structures Stack and Queue Data Structures
poongothai11
 
Unix / Linux Operating System introduction.
Unix / Linux Operating System introduction.
poongothai11
 
Introduction to Database Management Systems
Introduction to Database Management Systems
poongothai11
 
Open System Interconnection model and its layers.pdf
Open System Interconnection model and its layers.pdf
poongothai11
 
Computer Organization Introduction, Generations of Computer.pptx
Computer Organization Introduction, Generations of Computer.pptx
poongothai11
 
C Programming Language Introduction and C Tokens.pdf
C Programming Language Introduction and C Tokens.pdf
poongothai11
 
Stack and its operations, Queue and its operations
Stack and its operations, Queue and its operations
poongothai11
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Thread Concept: Multithreading, Creating thread using thread
Thread Concept: Multithreading, Creating thread using thread
poongothai11
 
Introduction to Data Structures, Data Structures using C.pptx
Introduction to Data Structures, Data Structures using C.pptx
poongothai11
 
Ad

Recently uploaded (20)

Gives a structured overview of the skills measured in the DP-700 exam
Gives a structured overview of the skills measured in the DP-700 exam
thehulk1299
 
CISA Certification And Training online..
CISA Certification And Training online..
Streling next pvt ltd
 
ndss2024xxxxxxxxxxxxxxxxx_slides (1).ppsx
ndss2024xxxxxxxxxxxxxxxxx_slides (1).ppsx
rnkaushal2
 
"Housefull 5" (.2025.) +Fu𝗅𝗅Mov𝗂e! Down𝗅oad Fre𝖾 𝟩𝟤𝟢𝗉, 𝟦𝟪𝟢𝗉 𝖧𝖣 & 𝟣𝟢𝟪𝟢𝗉
"Housefull 5" (.2025.) +Fu𝗅𝗅Mov𝗂e! Down𝗅oad Fre𝖾 𝟩𝟤𝟢𝗉, 𝟦𝟪𝟢𝗉 𝖧𝖣 & 𝟣𝟢𝟪𝟢𝗉
deltaforcedxb7
 
Pembuatan career yang baik dengan cara.pptx
Pembuatan career yang baik dengan cara.pptx
harun706371
 
physical_hazard.ppt-, sixjirixiifrr8fifk4kfickfkjk
physical_hazard.ppt-, sixjirixiifrr8fifk4kfickfkjk
ShrawanKumarTiwari
 
Using Social Media in Job Search June 2025
Using Social Media in Job Search June 2025
Bruce Bennett
 
Revolutionizing Environmental Compliance with AI.pdf
Revolutionizing Environmental Compliance with AI.pdf
Dorian F Corliss
 
A Guide for a Winning Interview June 2025
A Guide for a Winning Interview June 2025
Bruce Bennett
 
ACEN presentation / huddle from June 2025
ACEN presentation / huddle from June 2025
Mark Rauterkus
 
Garments Manufacturing, design, cutting and sewing of garments
Garments Manufacturing, design, cutting and sewing of garments
NaumanRafique9
 
S Pomeroy - Resume - Financial Leadership Role ATSV2 (06 13 25).pdf
S Pomeroy - Resume - Financial Leadership Role ATSV2 (06 13 25).pdf
ndhsshare1
 
Seniority List of Teachers 2025.pdf......
Seniority List of Teachers 2025.pdf......
shabrosa35196
 
2.2 Technical Proposal Writing - Developing a Concept Paper.pptx
2.2 Technical Proposal Writing - Developing a Concept Paper.pptx
OkonyaJacob2
 
Current Affairs for Prelims (Schemes) 2024 (1).pptx
Current Affairs for Prelims (Schemes) 2024 (1).pptx
malavikasprinklr
 
IISc-CDS-v2xxxxxxxxxxxxxcxxxxxx (1).potx
IISc-CDS-v2xxxxxxxxxxxxxcxxxxxx (1).potx
rnkaushal2
 
suruuuuuuuuxdvvvvvvvvvvvvvv ssssssrnbn bvcbvc
suruuuuuuuuxdvvvvvvvvvvvvvv ssssssrnbn bvcbvc
dineshkumarengg
 
Twilio Jobs Ghaziabad 673 Part Time Job in Uttar Pradesh.pdf
Twilio Jobs Ghaziabad 673 Part Time Job in Uttar Pradesh.pdf
infonaukridekhe
 
👉 Top 11 IT Companies in Hinjewadi You Should Know About
👉 Top 11 IT Companies in Hinjewadi You Should Know About
vaishalitraffictail
 
Algebra fjuvrufguisdhvjbfjivjgrbvnbvjhu
Algebra fjuvrufguisdhvjbfjivjgrbvnbvjhu
mikylamongale
 
Gives a structured overview of the skills measured in the DP-700 exam
Gives a structured overview of the skills measured in the DP-700 exam
thehulk1299
 
CISA Certification And Training online..
CISA Certification And Training online..
Streling next pvt ltd
 
ndss2024xxxxxxxxxxxxxxxxx_slides (1).ppsx
ndss2024xxxxxxxxxxxxxxxxx_slides (1).ppsx
rnkaushal2
 
"Housefull 5" (.2025.) +Fu𝗅𝗅Mov𝗂e! Down𝗅oad Fre𝖾 𝟩𝟤𝟢𝗉, 𝟦𝟪𝟢𝗉 𝖧𝖣 & 𝟣𝟢𝟪𝟢𝗉
"Housefull 5" (.2025.) +Fu𝗅𝗅Mov𝗂e! Down𝗅oad Fre𝖾 𝟩𝟤𝟢𝗉, 𝟦𝟪𝟢𝗉 𝖧𝖣 & 𝟣𝟢𝟪𝟢𝗉
deltaforcedxb7
 
Pembuatan career yang baik dengan cara.pptx
Pembuatan career yang baik dengan cara.pptx
harun706371
 
physical_hazard.ppt-, sixjirixiifrr8fifk4kfickfkjk
physical_hazard.ppt-, sixjirixiifrr8fifk4kfickfkjk
ShrawanKumarTiwari
 
Using Social Media in Job Search June 2025
Using Social Media in Job Search June 2025
Bruce Bennett
 
Revolutionizing Environmental Compliance with AI.pdf
Revolutionizing Environmental Compliance with AI.pdf
Dorian F Corliss
 
A Guide for a Winning Interview June 2025
A Guide for a Winning Interview June 2025
Bruce Bennett
 
ACEN presentation / huddle from June 2025
ACEN presentation / huddle from June 2025
Mark Rauterkus
 
Garments Manufacturing, design, cutting and sewing of garments
Garments Manufacturing, design, cutting and sewing of garments
NaumanRafique9
 
S Pomeroy - Resume - Financial Leadership Role ATSV2 (06 13 25).pdf
S Pomeroy - Resume - Financial Leadership Role ATSV2 (06 13 25).pdf
ndhsshare1
 
Seniority List of Teachers 2025.pdf......
Seniority List of Teachers 2025.pdf......
shabrosa35196
 
2.2 Technical Proposal Writing - Developing a Concept Paper.pptx
2.2 Technical Proposal Writing - Developing a Concept Paper.pptx
OkonyaJacob2
 
Current Affairs for Prelims (Schemes) 2024 (1).pptx
Current Affairs for Prelims (Schemes) 2024 (1).pptx
malavikasprinklr
 
IISc-CDS-v2xxxxxxxxxxxxxcxxxxxx (1).potx
IISc-CDS-v2xxxxxxxxxxxxxcxxxxxx (1).potx
rnkaushal2
 
suruuuuuuuuxdvvvvvvvvvvvvvv ssssssrnbn bvcbvc
suruuuuuuuuxdvvvvvvvvvvvvvv ssssssrnbn bvcbvc
dineshkumarengg
 
Twilio Jobs Ghaziabad 673 Part Time Job in Uttar Pradesh.pdf
Twilio Jobs Ghaziabad 673 Part Time Job in Uttar Pradesh.pdf
infonaukridekhe
 
👉 Top 11 IT Companies in Hinjewadi You Should Know About
👉 Top 11 IT Companies in Hinjewadi You Should Know About
vaishalitraffictail
 
Algebra fjuvrufguisdhvjbfjivjgrbvnbvjhu
Algebra fjuvrufguisdhvjbfjivjgrbvnbvjhu
mikylamongale
 
Ad

Exception Handling Multithreading: Fundamental of Exception; Exception types; Using try and catch; Multiple Catch.

  • 1. Unit - III Exception Handling and Multithreading What is Exception in Java?  Exceptions are events that occur during the execution of programs that disrupt the normal flow of instructions (e.g. divide by zero, array access out of bound, etc.).  Exception is an object which is thrown at runtime.  Exception objects can be thrown and caught. What is Exception Handling?  Exception Handling is a mechanism to handle runtime errors such as  ClassNotFoundException,  IOException,  SQLException,  RemoteException, etc. Advantage of Exception Handling  The advantage of exception handling is to maintain the normal flow of the application.  An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.
  • 2.  Example: statement 1; statement 2; statement 3; statement 4; statement 5;//exception occurs statement 6; statement 7; statement 8; statement 9; statement 10;  Suppose there are 10 statements in a Java program and an exception occurs at statement 5;  The rest of the code will not be executed, i.e., statements 6 to 10 will not be executed.  However, when we perform exception handling, the rest of the statements will be executed. That is why we use exception handling in Java. Hierarchy of Java Exception classes  The java.lang.Throwable class is the root class of Java Exception.  The hierarchy inherited by two subclasses:  Exception and  Error
  • 3. Exceptions are used to indicate many different types of error conditions.  JVM Errors:  OutOfMemoryError  StackOverflowError  LinkageError  System errors:  FileNotFoundException  IOException
  • 4.  SocketTimeoutException  Programming errors:  NullPointerException  ArrayIndexOutOfBoundsException  ArithmeticException Types of Exceptions  Java defines several types of exceptions that relate to its various class libraries.  Java also allows users to define their own exceptions. Exceptions can be categorized in two ways: 1. Built-in Exceptions  Checked Exception  Unchecked Exception 2. User-Defined Exceptions 1. Built-in Exceptions  Built-in exceptions are the exceptions that are available in Java libraries.
  • 5.  These exceptions are suitable to explain certain error situations. Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-time by the compiler. Unchecked Exceptions: The compiler will not check these exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare it, the program would not give a compilation error. 2. User-Defined Exceptions:  Users can also create exceptions, which are called ‘user-defined Exceptions’. Advantages of Exception Handling in Java are as follows: 1. Provision to Complete Program Execution 2. Easy Identification of Program Code and Error-Handling Code 3. Propagation of Errors 4. Meaningful Error Reporting 5. Identifying Error Types Common Scenarios of Java Exceptions  There are given some scenarios where unchecked exceptions may occur. They are as follows: 1) A scenario where ArithmeticException occurs  If we divide any number by zero, there occurs an ArithmeticException. int a=50/0; //ArithmeticException 2) A scenario where NullPointerException occurs  If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
  • 6. String s=null; System.out.println(s.length()); //NullPointerException 3) A scenario where NumberFormatException occurs  If the formatting of any variable or number is mismatched, it may result into NumberFormatException.  Suppose we have a string variable that has characters; converting this variable into digit will cause NumberFormatException. String s="abc"; int i=Integer.parseInt(s); //NumberFormatException 4) A scenario where ArrayIndexOutOfBoundsException occurs  When an array exceeds to it's size, the ArrayIndexOutOfBoundsException occurs.  There may be other reasons to occur ArrayIndexOutOfBoundsException. int a[]=new int[5]; a[10]=50; //ArrayIndexOutOfBoundsException
  • 7. Java Exception Keywords  Java provides five keywords that are used to handle the exception. Keyword Description Try  The "try" keyword is used to specify a block where we should place an exception code.  It means we can't use try block alone.  The try block must be followed by either catch or finally. Catch  The "catch" block is used to handle the exception.  It must be preceded by try block which means we can't use catch block alone. Finally  The "finally" block is used to execute the necessary 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 specifies that there may occur an exception in the method.  It doesn't throw an exception.  It is always used with method signature.
  • 8. Java try and catch  The try statement allows you to define a block of code to be tested for errors while it is being executed.  The catch statement allows you to define a block of code to be executed, if an error occurs in the try block. Java try block:  Java try block is used to enclose the code that might throw an exception.  It must be used within the method.  If an exception occurs at the particular statement in the try block, the rest of the block code will not execute.  So, it is recommended not to keep the code in try block that will not throw an exception.  Java try block must be followed by either catch or finally block. Syntax of Java try-catch: try { //code that may throw an exception } catch(Exception_class_Name ref) { } Syntax of try-finally block: Try { //code that may throw an exception } Finally { }
  • 9. Java catch block  Java catch block is used to handle the Exception by declaring the type of exception within the parameter.  The declared exception must be the parent class exception ( i.e., Exception)  The catch block must be used after the try block only.  You can use multiple catch block with a single try block. Internal Working of Java try-catch block:  The JVM firstly checks whether the exception is handled or not.  If exception is not handled, JVM provides a default exception handler that performs the following tasks:  Prints out exception description.  Prints the stack trace (Hierarchy of methods where the exception occurred).  Causes the program to terminate.
  • 10.  But if the application programmer handles the exception, the normal flow of the application is maintained, i.e., rest of the code is executed. Example1: Problem without exception handling  if we don't use a try-catch block. public class TryCatchExample1 { public static void main(String[] args) { int data=50/0; //may throw exception System.out.println("rest of the code"); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero Example 2: Solution by exception handling  Using java try-catch block. public class TryCatchExample2 { public static void main(String[] args) { try { int data=50/0; //may throw exception } //handling the exception catch(ArithmeticException e) { System.out.println(e); } System.out.println("rest of the code");
  • 11. } } Output: java.lang.ArithmeticException: / by zero rest of the code Example 3: In this example, we also kept the code in a try block that will not throw an exception. public class TryCatchExample3 { 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); } } } Output: java.lang.ArithmeticException: / by zero Here, we can see that if an exception occurs in the try block, the rest of the block code will not execute.
  • 12. Example 4: Here, we handle the exception using the parent class exception. public class TryCatchExample4 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception by using Exception class catch(Exception e) { System.out.println(e); } System.out.println("rest of the code"); } } Output: java.lang.ArithmeticException: / by zero rest of the code Example 5: to print a custom message on exception. public class TryCatchExample5 { public static void main(String[] args) { try { int data=50/0; //may throw exception } // handling the exception catch(Exception e)
  • 13. { // displaying the custom message System.out.println("Can't divided by zero"); } } } Output: Can't divided by zero Example 6: to resolve the exception in a catch block. public class TryCatchExample6 { public static void main(String[] args) { int i=50; int j=0; int data; try { data=i/j; //may throw exception } // handling the exception catch(Exception e) { // resolving the exception in catch block System.out.println(i/(j+2)); } } } Output: 25
  • 14. Java Multi-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.
  • 15. Example: java multi-catch block. 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"); } } OUTPUT Arithmetic Exception occurs rest of the code Java Nested try block:  In Java, using a try block inside another try block is permitted. It is called as nested try block.  For example, the inner try block can be used to handle ArrayIndexOutOfBoundsException while the outer try block can handle the ArithemeticException (division by zero).
  • 16. Syntax: .... //main try block try { statement 1; statement 2; //try catch block within another try block try { statement 3; statement 4; //try catch block within nested try block try { statement 5; statement 6; } catch(Exception e2) { //exception message } } catch(Exception e1) { //exception message } } //catch block of parent (outer) try block catch(Exception e3) { //exception message
  • 17. } .... Example: a try block within another try block for two different exceptions. public class NestedTryBlock{ public static void main(String args[]){ //outer try block try{ //inner try block 1 try{ System.out.println("going to divide by 0"); int b =39/0; } //catch block of inner try block 1 catch(ArithmeticException e) { System.out.println(e); } //inner try block 2 try{ int a[]=new int[5]; //assigning the value out of array bounds a[5]=4; } //catch block of inner try block 2 catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } System.out.println("other statement"); } //catch block of outer try block catch(Exception e) { System.out.println("handled the exception (outer catch)");
  • 18. } System.out.println("normal flow.."); } } Output: Java throw keyword  The Java throw keyword is used to throw an exception explicitly.  We can define our own set of conditions and throw an exception explicitly using throw keyword.  For example, we can throw ArithmeticException if we divide a number by another number.  Here, we just need to set the condition and throw exception using throw keyword. The syntax of the Java throw keyword is given below. throw Instance i.e., throw new exception_class("error message"); Example of throw IOException. throw new IOException("sorry device error"); Java throw keyword Example Example 1: Throwing Unchecked Exception  In this example, we have created a method named validate() that accepts an integer as a parameter.
  • 19.  If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. public class TestThrow1 { //function to check if person is eligible to vote or not public static void validate(int age) { if(age<18) { //throw Arithmetic exception if not eligible to vote throw new ArithmeticException("Person is not eligible to vote"); } else { System.out.println("Person is eligible to vote!!"); } } //main method public static void main(String args[]){ //calling the function validate(13); System.out.println("rest of the code..."); } } Example 2: Throwing Checked Exception Every subclass of Error and RuntimeException is an unchecked exception in java. A checked exception is everything else under the Throwable class. import java.io.*; public class TestThrow2 {
  • 20. //function to check if person is eligible to vote or not public static void method() throws FileNotFoundException { FileReader file = new FileReader("C:UsersAnuratiDesktopabc.txt"); BufferedReader fileInput = new BufferedReader(file); throw new FileNotFoundException(); } //main method public static void main(String args[]){ try { method(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("rest of the code..."); } } Output:
  • 21. Example 3: Throwing User-defined Exception exception is everything else under the Throwable class. TestThrow3.java // class represents user-defined exception class UserDefinedException extends Exception { public UserDefinedException(String str) { // Calling constructor of parent Exception super(str); } } // Class that uses above MyException public class TestThrow3 { public static void main(String args[]) { try { // throw an object of user defined exception throw new UserDefinedException("This is user-defined exception"); } catch (UserDefinedException ude) { System.out.println("Caught the exception"); // Print the message from MyException object System.out.println(ude.getMessage()); } } } Output:
  • 22. Java finally block Java finally block is a block used to execute important code such as closing the connection, etc. Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not. The finally block follows the try-catch block.
  • 23. Example: Case 1: When an exception does not occur  Java program does not throw any exception, and the finally block is executed after the try block. class TestFinallyBlock { public static void main(String args[]){ try{ //below code do not throw any exception int data=25/5; System.out.println(data); } //catch won't be executed catch(NullPointerException e){ System.out.println(e); } //executed regardless of exception occurred or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } OUTPUT Case 2: When an exception occur but not handled by the catch block  Here, the code throws an exception however the catch block cannot handle it.
  • 24.  Despite this, the finally block is executed after the try block and then the program terminates abnormally. public class TestFinallyBlock1{ public static void main(String args[]){ try { System.out.println("Inside the try block"); //below code throws divide by zero exception int data=25/0; System.out.println(data); } //cannot handle Arithmetic type exception //can only accept Null Pointer type exception catch(NullPointerException e){ System.out.println(e); } //executes regardless of exception occured or not finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } Output:
  • 25. Lab Program7:Write a java program to implement Exception Handling import java.io.*; class MyException extends Exception { private int detail; MyException(int a) { detail=a; } public String toString() { return "Minor with age less than 18 and you are only "+detail; } } class ExceptionDemo { static void compute(int x)throws MyException { if(x<18) throw new MyException(x); else System.out.println("You can voten"); } public static void main(String arg[]) { try { compute(20); compute(15); } catch(MyException e) { System.out.println("My Exception caught "+e); } finally { System.out.println("nYou are an Indian"); } } }