SlideShare a Scribd company logo
Exception Handling
Exception is an error event that can happen during the execution of a program and
disrupts its normal flow. Java provides a robust and object oriented way to handle
exception scenarios, known as Java “Exception Handling”.

Some of the reasons where exception occurs:
1) A user has entered invalid data.
2) A file that needs to be opened cannot be found.
3) A network connection has been lost in the middle of communications or the JVM
has run out of memory.
4) Some of these exceptions are caused by user error, others by programmer error,
and others by physical resources that have failed in some manner.
Exception Handling Keywords
Here is a list of most common checked and unchecked Java's Built-in
Exceptions.
try-catch :
A method catches an exception using a combination of the try and catch keywords. We
use try-catch block for exception handling in our code. try is the start of the block and
catch is at the end of try block to handle the exceptions. We can have multiple catch
blocks with a try and try-catch block can be nested also. catch block requires a
parameter that should be of type Exception.
try
{
//Protected code
}
catch(ExceptionName a1)
{
//Catch block
}
http://www.p2cinfotech.com

Phone: +1-732-546-3607
Exception Handling
Multiple catch Blocks:
A try block can be followed by multiple catch blocks. The syntax for multiple
catch blocks is:
try
{
//Protected code
}
catch(ExceptionType1 a1)
{
//Catch block
}
catch(ExceptionType2 a2)
{
//Catch block
}
catch(ExceptionType3 a3)
{
//Catch block
}
The previous statements demonstrate three catch blocks, but you can have any number
of them after a single try. If an exception occurs in the protected code, the exception is
thrown to the first catch block in the list. If the data type of the exception thrown
matches ExceptionType1, it gets caught there. If not, the exception passes down to the
second catch statement. This continues until the exception either is caught or falls
through all catches, in which case the current method stops execution and the
exception is thrown down to the previous method on the call stack.
throw :
We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them. Sometime we might want to generate
exception explicitly in our code, for example in a user authentication program we should
throw exception to client if the password is null. throw keyword is used to throw
exception to the runtime to handle it. Program execution stops while encountering throw
statement and the closest catch statement is checked for matching type of exception.

http://www.p2cinfotech.com

Phone: +1-732-546-3607
Exception Handling
Example:
Class Test
{
Static void avg()
{
Try
{
throw new ArithmeticException(“demo”);
}
Catch(ArithmeticException e)
{
System.out.println(“Exception Caught”);
}
}
Public static void main(String args[])
{
avg()
}
}
throws :
When we are throwing any exception in a method and not handling it, then we need to
use throws keyword in method signature to let caller program know the exceptions that
might be thrown by the method. The caller method might handle these exceptions or
propagate it to it’s caller method using throws keyword. We can provide multiple
exceptions in the throws clause and it can be used with main() method also.

http://www.p2cinfotech.com

Phone: +1-732-546-3607
Exception Handling
Example:
Class Test
{
Static void check() throws Arithmetic Expression
{
System.out.println(“Inside check function”);
throw new ArithmeticException(“demo”);
}
Public static void main(String args[])
{
Try
{
Check();
}
Catch(ArithmeticException e)
{
System.out.println(“caught” +e);
}
}
}
finally :
finally block is optional and can be used only with try-catch block. Since exception halts
the process of execution, we might have some resources open that will not get closed,
so we can use finally block. finally block gets executed always, whether exception
occurred or not.

http://www.p2cinfotech.com

Phone: +1-732-546-3607
Exception Handling
Example:
class ExceptionTest
{
public static void main(String args[])
{
int a[]= new int[2];
System.out.println(“out of try”);
try
{
System.out.println(“access invalid element” + a[3]);
}
finally
{
System.out.println(“finally is always executed”);
}
}
}
Common Exceptions:
In Java, it is possible to define two catergories of Exceptions and Errors.
JVM Exceptions: These are exceptions/errors that are exclusively or logically thrown by
the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException.
Programmatic exceptions: These exceptions are thrown explicitly by the application or
the API programmers
Examples: IllegalArgumentException, IllegalStateException.

http://www.p2cinfotech.com

Phone: +1-732-546-3607
Exception Handling
Exception Hierarchy:
As stated earlier, when any exception is raised an exception object is getting created.
Java Exceptions are hierarchical and inheritanceis used to categorize different types of
exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two
child objects – Error and Exception. Exceptions are further divided into checked
exceptions and runtime exception.
1. Errors:
Errors are exceptional scenarios that are out of scope of application and it’s not
possible to anticipate and recover from them, for example hardware failure, JVM
crash or out of memory error. That’s why we have a separate hierarchy of errors
and we should not try to handle these situations. Some of the common Errors are
OutOfMemoryError and StackOverflowError.
2. Checked Exceptions:
Checked Exceptions are exceptional scenarios that we can anticipate in a program
and try to recover from it, for example FileNotFoundException. We should catch this
exception and provide useful message to user and log it properly for debugging
purpose. Exception is the parent class of all Checked Exceptions and if we are
throwing a checked exception, we must catch it in the same method or we have to
propagate it to the caller using throws keyword.
3. Runtime Exception:
Runtime Exceptions are cause by bad programming, for example trying to retrieve
an element from the Array. We should check the length of array first before trying to
retrieve the element otherwise it might throwArrayIndexOutOfBoundException at
runtime. RuntimeException is the parent class of all runtime exceptions. If we are
throwing any runtime exception in a method, it’s not required to specify them in the
method signature throws clause. Runtime exceptions can be avoided with better
programming.

http://www.p2cinfotech.com

Phone: +1-732-546-3607
Exception Handling

Useful Exception Methods:
Some of the useful methods of Throwable class are;
1. public String getMessage() – This method returns the message String of Throwable
and the message can be provided while creating the exception through it’s
constructor.
2. public String getLocalizedMessage() – This method is provided so that subclasses
can override it to provide locale specific message to the calling program. Throwable
class implementation of this method simply use getMessage() method to return the
exception message.
3. public synchronized Throwable getCause() – This method returns the cause of the
exception or null id the cause is unknown.
4. public String toString() – This method returns the information about Throwable in
String format, the returned String contains the name of Throwable class and
localized message.
5. public void printStackTrace() – This method prints the stack trace information to the
standard error stream, this method is overloaded and we can pass PrintStream or
PrintWriter as argument to write the stack trace information to the file or stream.

http://www.p2cinfotech.com

Phone: +1-732-546-3607
Ad

More Related Content

What's hot (20)

RichControl in Asp.net
RichControl in Asp.netRichControl in Asp.net
RichControl in Asp.net
Bhumivaghasiya
 
Visual programming lecture
Visual programming lecture Visual programming lecture
Visual programming lecture
AqsaHayat3
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to Sharding
MongoDB
 
Introduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 FundamentalsIntroduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 Fundamentals
Sanay Kumar
 
C# Constructors
C# ConstructorsC# Constructors
C# Constructors
Prem Kumar Badri
 
Making decision and repeating in PHP
Making decision and repeating  in PHPMaking decision and repeating  in PHP
Making decision and repeating in PHP
Kamal Acharya
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
myrajendra
 
Android Operating System Architecture
Android Operating System ArchitectureAndroid Operating System Architecture
Android Operating System Architecture
DINESH KUMAR ARIVARASAN
 
Interpreters & Debuggers
Interpreters  &  DebuggersInterpreters  &  Debuggers
Interpreters & Debuggers
Malek Sumaiya
 
The msg box function and the messagebox class
The msg box function and the messagebox classThe msg box function and the messagebox class
The msg box function and the messagebox class
Faisal Aziz
 
Java constructors
Java constructorsJava constructors
Java constructors
QUONTRASOLUTIONS
 
C#.NET
C#.NETC#.NET
C#.NET
gurchet
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Java Swing
Java SwingJava Swing
Java Swing
Arkadeep Dey
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
Bagzzz
 
Asp.net.
Asp.net.Asp.net.
Asp.net.
Naveen Sihag
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
Introduction to c#
Introduction to c#Introduction to c#
Introduction to c#
OpenSource Technologies Pvt. Ltd.
 
Database Design
Database DesignDatabase Design
Database Design
learnt
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
Chaffey College
 
RichControl in Asp.net
RichControl in Asp.netRichControl in Asp.net
RichControl in Asp.net
Bhumivaghasiya
 
Visual programming lecture
Visual programming lecture Visual programming lecture
Visual programming lecture
AqsaHayat3
 
Introduction to Sharding
Introduction to ShardingIntroduction to Sharding
Introduction to Sharding
MongoDB
 
Introduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 FundamentalsIntroduction to Visual Basic 6.0 Fundamentals
Introduction to Visual Basic 6.0 Fundamentals
Sanay Kumar
 
Making decision and repeating in PHP
Making decision and repeating  in PHPMaking decision and repeating  in PHP
Making decision and repeating in PHP
Kamal Acharya
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
myrajendra
 
Interpreters & Debuggers
Interpreters  &  DebuggersInterpreters  &  Debuggers
Interpreters & Debuggers
Malek Sumaiya
 
The msg box function and the messagebox class
The msg box function and the messagebox classThe msg box function and the messagebox class
The msg box function and the messagebox class
Faisal Aziz
 
Visual Programming
Visual ProgrammingVisual Programming
Visual Programming
Bagzzz
 
Database Design
Database DesignDatabase Design
Database Design
learnt
 
Ch 3 event driven programming
Ch 3 event driven programmingCh 3 event driven programming
Ch 3 event driven programming
Chaffey College
 

Viewers also liked (20)

Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Yaazli International AngularJS 5 Training
Yaazli International AngularJS 5 TrainingYaazli International AngularJS 5 Training
Yaazli International AngularJS 5 Training
Arjun Sridhar U R
 
Non ieee dot net projects list
Non  ieee dot net projects list Non  ieee dot net projects list
Non ieee dot net projects list
Mumbai Academisc
 
Core java online training
Core java online trainingCore java online training
Core java online training
Glory IT Technologies Pvt. Ltd.
 
Java quick reference v2
Java quick reference v2Java quick reference v2
Java quick reference v2
Christopher Akinlade
 
Toolbarexample
ToolbarexampleToolbarexample
Toolbarexample
yugandhar vadlamudi
 
02basics
02basics02basics
02basics
Waheed Warraich
 
For Loops and Variables in Java
For Loops and Variables in JavaFor Loops and Variables in Java
For Loops and Variables in Java
Pokequesthero
 
Yaazli International Spring Training
Yaazli International Spring Training Yaazli International Spring Training
Yaazli International Spring Training
Arjun Sridhar U R
 
09events
09events09events
09events
Waheed Warraich
 
Yaazli International Hibernate Training
Yaazli International Hibernate TrainingYaazli International Hibernate Training
Yaazli International Hibernate Training
Arjun Sridhar U R
 
Savr
SavrSavr
Savr
Shahar Barsheshet
 
Yaazli International Web Project Workshop
Yaazli International Web Project WorkshopYaazli International Web Project Workshop
Yaazli International Web Project Workshop
Arjun Sridhar U R
 
DIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image ManipulationDIWE - Using Extensions and Image Manipulation
DIWE - Using Extensions and Image Manipulation
Rasan Samarasinghe
 
Non ieee java projects list
Non  ieee java projects list Non  ieee java projects list
Non ieee java projects list
Mumbai Academisc
 
Java Basic Operators
Java Basic OperatorsJava Basic Operators
Java Basic Operators
Shahid Rasheed
 
Singleton pattern
Singleton patternSingleton pattern
Singleton pattern
yugandhar vadlamudi
 
DIWE - Multimedia Technologies
DIWE - Multimedia TechnologiesDIWE - Multimedia Technologies
DIWE - Multimedia Technologies
Rasan Samarasinghe
 
Yaazli International Java Training
Yaazli International Java Training Yaazli International Java Training
Yaazli International Java Training
Arjun Sridhar U R
 
java swing
java swingjava swing
java swing
Waheed Warraich
 
Ad

Similar to Java Exception handling (20)

Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programmingException‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
ushakiranv110
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Exception‐Handling in object oriented programming
Exception‐Handling in object oriented programmingException‐Handling in object oriented programming
Exception‐Handling in object oriented programming
Parameshwar Maddela
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
Kuntal Bhowmick
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
RubaNagarajan
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
SakkaravarthiS1
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
ushakiranv110
 
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...Exception Handling Multithreading: Fundamental of Exception; Exception types;...
Exception Handling Multithreading: Fundamental of Exception; Exception types;...
poongothai11
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
Exception Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptxException Handling,finally,catch,throw,throws,try.pptx
Exception Handling,finally,catch,throw,throws,try.pptx
ArunPatrick2
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Ad

More from Garuda Trainings (15)

SAP BI 7.0 Info Providers
SAP BI 7.0 Info ProvidersSAP BI 7.0 Info Providers
SAP BI 7.0 Info Providers
Garuda Trainings
 
Short definitions of all testing types
Short definitions of all testing typesShort definitions of all testing types
Short definitions of all testing types
Garuda Trainings
 
Software testing life cycle
Software testing life cycleSoftware testing life cycle
Software testing life cycle
Garuda Trainings
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings
 
Performance testing interview questions and answers
Performance testing interview questions and answersPerformance testing interview questions and answers
Performance testing interview questions and answers
Garuda Trainings
 
Loadrunner interview questions and answers
Loadrunner interview questions and answersLoadrunner interview questions and answers
Loadrunner interview questions and answers
Garuda Trainings
 
Business analysis interview question and answers
Business analysis interview question and answersBusiness analysis interview question and answers
Business analysis interview question and answers
Garuda Trainings
 
Quality center interview questions and answers
Quality center interview questions and answersQuality center interview questions and answers
Quality center interview questions and answers
Garuda Trainings
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
Garuda Trainings
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for Java
Garuda Trainings
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Dot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineDot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement online
Garuda Trainings
 
Interview questions and answers for quality assurance
Interview questions and answers for quality assuranceInterview questions and answers for quality assurance
Interview questions and answers for quality assurance
Garuda Trainings
 
Unix commands in etl testing
Unix commands in etl testingUnix commands in etl testing
Unix commands in etl testing
Garuda Trainings
 
SQL for ETL Testing
SQL for ETL TestingSQL for ETL Testing
SQL for ETL Testing
Garuda Trainings
 
Short definitions of all testing types
Short definitions of all testing typesShort definitions of all testing types
Short definitions of all testing types
Garuda Trainings
 
Software testing life cycle
Software testing life cycleSoftware testing life cycle
Software testing life cycle
Garuda Trainings
 
Fundamental classes in java
Fundamental classes in javaFundamental classes in java
Fundamental classes in java
Garuda Trainings
 
Performance testing interview questions and answers
Performance testing interview questions and answersPerformance testing interview questions and answers
Performance testing interview questions and answers
Garuda Trainings
 
Loadrunner interview questions and answers
Loadrunner interview questions and answersLoadrunner interview questions and answers
Loadrunner interview questions and answers
Garuda Trainings
 
Business analysis interview question and answers
Business analysis interview question and answersBusiness analysis interview question and answers
Business analysis interview question and answers
Garuda Trainings
 
Quality center interview questions and answers
Quality center interview questions and answersQuality center interview questions and answers
Quality center interview questions and answers
Garuda Trainings
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
Garuda Trainings
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for Java
Garuda Trainings
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
Garuda Trainings
 
Dot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement onlineDot net Online Training | .Net Training and Placement online
Dot net Online Training | .Net Training and Placement online
Garuda Trainings
 
Interview questions and answers for quality assurance
Interview questions and answers for quality assuranceInterview questions and answers for quality assurance
Interview questions and answers for quality assurance
Garuda Trainings
 
Unix commands in etl testing
Unix commands in etl testingUnix commands in etl testing
Unix commands in etl testing
Garuda Trainings
 

Recently uploaded (20)

GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - WorksheetCBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
CBSE - Grade 8 - Science - Chemistry - Metals and Non Metals - Worksheet
Sritoma Majumder
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulsepulse  ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
pulse ppt.pptx Types of pulse , characteristics of pulse , Alteration of pulse
sushreesangita003
 

Java Exception handling

  • 1. Exception Handling Exception is an error event that can happen during the execution of a program and disrupts its normal flow. Java provides a robust and object oriented way to handle exception scenarios, known as Java “Exception Handling”. Some of the reasons where exception occurs: 1) A user has entered invalid data. 2) A file that needs to be opened cannot be found. 3) A network connection has been lost in the middle of communications or the JVM has run out of memory. 4) Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. Exception Handling Keywords Here is a list of most common checked and unchecked Java's Built-in Exceptions. try-catch : A method catches an exception using a combination of the try and catch keywords. We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception. try { //Protected code } catch(ExceptionName a1) { //Catch block } http://www.p2cinfotech.com Phone: +1-732-546-3607
  • 2. Exception Handling Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks is: try { //Protected code } catch(ExceptionType1 a1) { //Catch block } catch(ExceptionType2 a2) { //Catch block } catch(ExceptionType3 a3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack. throw : We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it. Program execution stops while encountering throw statement and the closest catch statement is checked for matching type of exception. http://www.p2cinfotech.com Phone: +1-732-546-3607
  • 3. Exception Handling Example: Class Test { Static void avg() { Try { throw new ArithmeticException(“demo”); } Catch(ArithmeticException e) { System.out.println(“Exception Caught”); } } Public static void main(String args[]) { avg() } } throws : When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also. http://www.p2cinfotech.com Phone: +1-732-546-3607
  • 4. Exception Handling Example: Class Test { Static void check() throws Arithmetic Expression { System.out.println(“Inside check function”); throw new ArithmeticException(“demo”); } Public static void main(String args[]) { Try { Check(); } Catch(ArithmeticException e) { System.out.println(“caught” +e); } } } finally : finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not. http://www.p2cinfotech.com Phone: +1-732-546-3607
  • 5. Exception Handling Example: class ExceptionTest { public static void main(String args[]) { int a[]= new int[2]; System.out.println(“out of try”); try { System.out.println(“access invalid element” + a[3]); } finally { System.out.println(“finally is always executed”); } } } Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. JVM Exceptions: These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException. Programmatic exceptions: These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException. http://www.p2cinfotech.com Phone: +1-732-546-3607
  • 6. Exception Handling Exception Hierarchy: As stated earlier, when any exception is raised an exception object is getting created. Java Exceptions are hierarchical and inheritanceis used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception. 1. Errors: Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That’s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and StackOverflowError. 2. Checked Exceptions: Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exception is the parent class of all Checked Exceptions and if we are throwing a checked exception, we must catch it in the same method or we have to propagate it to the caller using throws keyword. 3. Runtime Exception: Runtime Exceptions are cause by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throwArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions. If we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming. http://www.p2cinfotech.com Phone: +1-732-546-3607
  • 7. Exception Handling Useful Exception Methods: Some of the useful methods of Throwable class are; 1. public String getMessage() – This method returns the message String of Throwable and the message can be provided while creating the exception through it’s constructor. 2. public String getLocalizedMessage() – This method is provided so that subclasses can override it to provide locale specific message to the calling program. Throwable class implementation of this method simply use getMessage() method to return the exception message. 3. public synchronized Throwable getCause() – This method returns the cause of the exception or null id the cause is unknown. 4. public String toString() – This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message. 5. public void printStackTrace() – This method prints the stack trace information to the standard error stream, this method is overloaded and we can pass PrintStream or PrintWriter as argument to write the stack trace information to the file or stream. http://www.p2cinfotech.com Phone: +1-732-546-3607