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.garudatrainings.com

Phone: +1-508-841-6144
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.garudatrainings.com

Phone: +1-508-841-6144
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 :

http://www.garudatrainings.com

Phone: +1-508-841-6144
Exception Handling
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.

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);
}
}
http://www.garudatrainings.com

Phone: +1-508-841-6144
Exception Handling
}
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.
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.
http://www.garudatrainings.com

Phone: +1-508-841-6144
Exception Handling
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.

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:

http://www.garudatrainings.com

Phone: +1-508-841-6144
Exception Handling
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.

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.
http://www.garudatrainings.com

Phone: +1-508-841-6144
Exception Handling

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.garudatrainings.com

Phone: +1-508-841-6144

More Related Content

What's hot

Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
parag
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
Tanmoy Roy
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
Lemi Orhan Ergin
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
Deepak Sharma
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
Exception handling
Exception handlingException handling
Exception handling
Raja Sekhar
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
exception handling
exception handlingexception handling
exception handling
Manav Dharman
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
Arjun Shanka
 
Exception handler
Exception handler Exception handler
Exception handler
dishni
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Reddhi Basu
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
Exception handling
Exception handlingException handling
Exception handling
Ardhendu Nandi
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
Garuda Trainings
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 

What's hot (20)

Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Best Practices in Exception Handling
Best Practices in Exception HandlingBest Practices in Exception Handling
Best Practices in Exception Handling
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Java exception
Java exception Java exception
Java exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
exception handling
exception handlingexception handling
exception handling
 
javaexceptions
javaexceptionsjavaexceptions
javaexceptions
 
Exception handler
Exception handler Exception handler
Exception handler
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 

Viewers also liked

Accountant cover letter
Accountant cover letterAccountant cover letter
Accountant cover letter
julietharris
 
Basketball
BasketballBasketball
Basketball
Cintia0093
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
Garuda Trainings
 
Accounts manager cover letter
Accounts manager cover letterAccounts manager cover letter
Accounts manager cover letter
julietharris
 
Accounting manager cover letter
Accounting manager cover letterAccounting manager cover letter
Accounting manager cover letter
julietharris
 
Account executive cover letter
Account executive cover letterAccount executive cover letter
Account executive cover letter
julietharris
 
Accounts assistant cover letter
Accounts assistant cover letterAccounts assistant cover letter
Accounts assistant cover letter
julietharris
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
Garuda Trainings
 

Viewers also liked (9)

Accountant cover letter
Accountant cover letterAccountant cover letter
Accountant cover letter
 
Basketball
BasketballBasketball
Basketball
 
Software development life cycle
Software development life cycleSoftware development life cycle
Software development life cycle
 
LA MÉTÉO
LA MÉTÉOLA MÉTÉO
LA MÉTÉO
 
Accounts manager cover letter
Accounts manager cover letterAccounts manager cover letter
Accounts manager cover letter
 
Accounting manager cover letter
Accounting manager cover letterAccounting manager cover letter
Accounting manager cover letter
 
Account executive cover letter
Account executive cover letterAccount executive cover letter
Account executive cover letter
 
Accounts assistant cover letter
Accounts assistant cover letterAccounts assistant cover letter
Accounts assistant cover letter
 
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda TrainingsSAP ABAP Latest Interview Questions with Answers by Garuda Trainings
SAP ABAP Latest Interview Questions with Answers by Garuda Trainings
 

Similar to Exception handling

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
 
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-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 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.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
Nagaraju Pamarthi
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
EduclentMegasoftel
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
TharuniDiddekunta
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
ushakiranv110
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
primevideos176
 
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
 
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
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
Rakesh Madugula
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Kavitha713564
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
DrHemlathadhevi
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.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
 

Similar to Exception handling (20)

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
 
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
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
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
 
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;...
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling basic
Exception handling basicException handling basic
Exception handling basic
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
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
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
 

More from Garuda Trainings

TIBCO Latest Interview Questions with Answers by Garuda Trainings
TIBCO Latest Interview Questions with Answers by Garuda TrainingsTIBCO Latest Interview Questions with Answers by Garuda Trainings
TIBCO Latest Interview Questions with Answers by Garuda Trainings
Garuda Trainings
 
Cloud computing Latest Interview Questions with Answers by Garuda Trainings
Cloud computing Latest Interview Questions with Answers by Garuda TrainingsCloud computing Latest Interview Questions with Answers by Garuda Trainings
Cloud computing Latest Interview Questions with Answers by Garuda Trainings
Garuda Trainings
 
Create generic delta
Create generic deltaCreate generic delta
Create generic delta
Garuda Trainings
 
Qa interview questions and answers
Qa interview questions and answersQa interview questions and answers
Qa interview questions and answers
Garuda Trainings
 
Qa interview questions and answers for placements
Qa interview questions and answers for placementsQa interview questions and answers for placements
Qa interview questions and answers for placements
Garuda Trainings
 
Exception handling
Exception handlingException handling
Exception handling
Garuda Trainings
 

More from Garuda Trainings (6)

TIBCO Latest Interview Questions with Answers by Garuda Trainings
TIBCO Latest Interview Questions with Answers by Garuda TrainingsTIBCO Latest Interview Questions with Answers by Garuda Trainings
TIBCO Latest Interview Questions with Answers by Garuda Trainings
 
Cloud computing Latest Interview Questions with Answers by Garuda Trainings
Cloud computing Latest Interview Questions with Answers by Garuda TrainingsCloud computing Latest Interview Questions with Answers by Garuda Trainings
Cloud computing Latest Interview Questions with Answers by Garuda Trainings
 
Create generic delta
Create generic deltaCreate generic delta
Create generic delta
 
Qa interview questions and answers
Qa interview questions and answersQa interview questions and answers
Qa interview questions and answers
 
Qa interview questions and answers for placements
Qa interview questions and answers for placementsQa interview questions and answers for placements
Qa interview questions and answers for placements
 
Exception handling
Exception handlingException handling
Exception handling
 

Recently uploaded

5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf
Alliance Jobs
 
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
2zjra9bn
 
一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理
一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理
一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理
pxyhy
 
Introducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptxIntroducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptx
FauzanHarits1
 
0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf
Thomas GIRARD BDes
 
一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理
一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理
一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理
pxyhy
 
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
2zjra9bn
 
RECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdf
RECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdfRECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdf
RECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdf
AlessandroMartins454470
 
lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789
Ghh
 
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
taqyea
 
Leadership Ambassador club Adventist module
Leadership Ambassador club Adventist moduleLeadership Ambassador club Adventist module
Leadership Ambassador club Adventist module
kakomaeric00
 
一比一原版(UVic毕业证)维多利亚大学毕业证如何办理
一比一原版(UVic毕业证)维多利亚大学毕业证如何办理一比一原版(UVic毕业证)维多利亚大学毕业证如何办理
一比一原版(UVic毕业证)维多利亚大学毕业证如何办理
pxyhy
 
A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024
Bruce Bennett
 
labb123456789123456789123456789123456789
labb123456789123456789123456789123456789labb123456789123456789123456789123456789
labb123456789123456789123456789123456789
Ghh
 
原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样
原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样
原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样
atwvhyhm
 
一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理
一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理
一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理
yuhofha
 
一比一原版(YU毕业证)约克大学毕业证如何办理
一比一原版(YU毕业证)约克大学毕业证如何办理一比一原版(YU毕业证)约克大学毕业证如何办理
一比一原版(YU毕业证)约克大学毕业证如何办理
yuhofha
 
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
dsnow9802
 
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
MuhammadWaqasBaloch1
 
Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024
SnapJob
 

Recently uploaded (20)

5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf5 Common Mistakes to Avoid During the Job Application Process.pdf
5 Common Mistakes to Avoid During the Job Application Process.pdf
 
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
在线制作加拿大萨省大学毕业证文凭证书实拍图原版一模一样
 
一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理
一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理
一比一原版(SFU毕业证)西蒙弗雷泽大学毕业证如何办理
 
Introducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptxIntroducing Gopay Mobile App For Environment.pptx
Introducing Gopay Mobile App For Environment.pptx
 
0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf0624.speakingengagementsandteaching-01.pdf
0624.speakingengagementsandteaching-01.pdf
 
一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理
一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理
一比一原版(UBC毕业证)不列颠哥伦比亚大学毕业证如何办理
 
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
官方认证美国旧金山州立大学毕业证学位证书案例原版一模一样
 
RECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdf
RECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdfRECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdf
RECOGNITION AWARD 13 - TO ALESSANDRO MARTINS.pdf
 
lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789lab.123456789123456789123456789123456789
lab.123456789123456789123456789123456789
 
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
一比一原版布拉德福德大学毕业证(bradford毕业证)如何办理
 
Leadership Ambassador club Adventist module
Leadership Ambassador club Adventist moduleLeadership Ambassador club Adventist module
Leadership Ambassador club Adventist module
 
一比一原版(UVic毕业证)维多利亚大学毕业证如何办理
一比一原版(UVic毕业证)维多利亚大学毕业证如何办理一比一原版(UVic毕业证)维多利亚大学毕业证如何办理
一比一原版(UVic毕业证)维多利亚大学毕业证如何办理
 
A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024A Guide to a Winning Interview June 2024
A Guide to a Winning Interview June 2024
 
labb123456789123456789123456789123456789
labb123456789123456789123456789123456789labb123456789123456789123456789123456789
labb123456789123456789123456789123456789
 
原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样
原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样
原版制作(RMIT毕业证书)墨尔本皇家理工大学毕业证在读证明一模一样
 
一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理
一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理
一比一原版(TMU毕业证)多伦多都会大学毕业证如何办理
 
一比一原版(YU毕业证)约克大学毕业证如何办理
一比一原版(YU毕业证)约克大学毕业证如何办理一比一原版(YU毕业证)约克大学毕业证如何办理
一比一原版(YU毕业证)约克大学毕业证如何办理
 
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
Jill Pizzola's Tenure as Senior Talent Acquisition Partner at THOMSON REUTERS...
 
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
Status of Women in Pakistan.pptxStatus of Women in Pakistan.pptx
 
Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024Job Finding Apps Everything You Need to Know in 2024
Job Finding Apps Everything You Need to Know in 2024
 

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.garudatrainings.com Phone: +1-508-841-6144
  • 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.garudatrainings.com Phone: +1-508-841-6144
  • 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 : http://www.garudatrainings.com Phone: +1-508-841-6144
  • 4. Exception Handling 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. 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); } } http://www.garudatrainings.com Phone: +1-508-841-6144
  • 5. Exception Handling } 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. 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. http://www.garudatrainings.com Phone: +1-508-841-6144
  • 6. Exception Handling 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. 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: http://www.garudatrainings.com Phone: +1-508-841-6144
  • 7. Exception Handling 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. 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. http://www.garudatrainings.com Phone: +1-508-841-6144
  • 8. Exception Handling 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.garudatrainings.com Phone: +1-508-841-6144