SlideShare a Scribd company logo
- Arulkumar V
Assistant Professor, SECE
Exception Handling
Guess the Output:
12/19/20172
public class Arithmetic {
public static void main(String[] Geek)
{
Integer a = 2;
Integer b;
b = a / 0;
System.out.println("Value of b is:"
+b);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at
Arithmatic.main(Arithmatic.java:7)
Introduction
12/19/20173
 An exception is an abnormal condition that
arises in a code sequence at run time. In other
words, an exception is a run-time error.
 In Java it is handled using 5 keywords
try
catch
throw
throws
finally
Using Keywords:
12/19/20174
try – A block of source code that is to be
monitored for exception
catch – It handles the specific type of exception
along with the try block.
throw – It is used to throw specific exception
from the program code.
throws – It specifies the exception that can be
thrown by a particular method.
finally – it specifies the code that must be
executed even though exception may or may not
be occur
Note:
1. For ever try block there exist the cache block.
Handling try-cache block:
12/19/20175
try block
Exception
object gets
created
here
Throws
Exception catch block
Object
Exception
handler
Exception
causing
statements
Exception
Handling
statements
Cont..,
12/19/20176
 The statement(s) that are likely to
cause an exception are enclosed
within a try block. For these
statements the exception is thrown.
 There is another block defined by
the keyword catch which is
responsible for handling the
exception thrown by the try catch
block.
 As soon as exception occurs it is
handled by the catch block.
 The cache block is added
immediately after the try block
Syntax of try- cache:
12/19/20177
try
{
//exception gets generated here
}
Catch(Type_of_Exception e)
{
//exception is handled here
}
Guess the Output:
12/19/20178
public class Arithmetic {
public static void main(String[] Geek)
{
Integer a = 2;
Integer b;
try
{
b = a / 0;
}
catch (ArithmeticException e)
{
System.out.println(e + "Exception occurs");
}
System.out.println("Exception Example Program");
}
Output:
java.lang.ArithmeticException: / by
zeroException occurs
Exception Example Program
Hierarchy of Exception classes
12/19/20179
Error
12/19/201710
 Error is irrecoverable
 e.g. OutOfMemoryError,
VirtualMachineError, AssertionError
etc.
throw keyword:
12/19/201711
 It is used to explicitly throw an exception.
 We can throw either checked or unchecked
exception.
 The throw keyword is mainly used to throw
custom exception.
throws keyword:
12/19/201712
 If a method is capable of causing an exception
that it does not handle, it must specify this
behavior so that callers of the method can
guard themselves against that exception.
 You do this by including a throws clause in the
method’s declaration.
 A throws clause lists the types of exceptions
that a method might throw.
throws keyword:
12/19/201713
 This is necessary for all exceptions, except
those of type Error or RuntimeException, or
any of their subclasses.
 All other exceptions that a method can throw
must be declared in the throws clause.
 If they are not, a compile-time error will result
throws Syntax:
12/19/201714
type method-name(parameter-list)
throws exception-list
{
// body of method
}
Eg:
static void validate (int age)
throws InvalidAgeException
throw & throws Example:
12/19/201715
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super (s); System.out.println(s); }
}
public class ExceptionDemo {
static void validate (int age) throws
InvalidAgeException {
if (age<18)
throw new InvalidAgeException("not
valid");
else
System.out.println("welcome to vote");
}
throw Example:
12/19/201716
public static void main (String args[]){
try{
validate(13);
}
catch (Exception m){
System.out.println("Exception occurred: "+m);
}
System.out.println("rest of the code...");
}
}
Output:
not valid
Exception occurred: InvalidAgeException: not valid
rest of the code...
Difference between throw and throws
keyword:
12/19/201717
Sl.
No
throw throws
1
It is used to explicitly throw an
exception
Used to declare and exception
2 It is followed by an instance It is followed by class
3
throw is used within the
method.
throws is used with the method
signature.
4
You cannot throw multiple
exception
You can declare multiple
exception e.g.
public void method()throws
IOException,SQLException.
Uncaught Exception
12/19/201718
 If there exist some code in the source program
which may cause an exception and if the
programmer does not handle this exception
then java runtime system raises the exception.
Uncaught Exception Example:
12/19/201719
public class Arithmetic {
public static void main(String[] Geek)
{
Integer a = 2;
Integer b;
b = a / 0;
System.out.println("Value of b is:"
+b);
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero at
Arithmatic.main(Arithmatic.java:7)
Multiple catch block:
12/19/201720
 If you have to perform different tasks at the
occurrence of different Exceptions, use multiple
catch block.
 Note:
 At a time only one Exception is occurred 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.
Multiple catch block Example 1:
12/19/201721
public class Main1{
public static void main(String args[]){
try{ int a[]=new int[5];
a[5]=30/0; }
catch(ArithmeticException e){
System.out.println(e+" - task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed"); }
catch(Exception e){
System.out.println("common task completed"); }
System.out.println("rest of the code...");
}
}
Output:
Task1 is completed
rest of the code…
Multiple catch block Example2:
12/19/201722
public class Main1{
public static void main(String args[]){
try{ int a[]=new int[5];
a[5]=30/0; }
catch(Exception e){
System.out.println("common task completed"); }
catch(ArithmeticException e){
System.out.println(e+" - task1 is completed"); }
catch(ArrayIndexOutOfBoundsException e){
System.out.println("task 2 completed"); }
System.out.println("rest of the code...");
}
}
Output:
Compile-time error
Nested try block:
12/19/201723
 try block within a try block is known as nested
try block.
 Sometimes a situation may arise where a part
of a block may cause one error and the entire
block itself may cause another error.
 In such cases, exception handlers have to be
nested
Syntax of nested try block:
12/19/201724
try
{
statement 1;
statement 2;
try
{ statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
Nested try Example:
12/19/201725
public class Main2{
public static void main(String args[]){
try{
try{ System.out.println("going to divide");
int b =39/0;
}
catch (ArithmeticException e){
System.out.println(e); }
try{ int a[]=new int[5];
a[5]=4;
}
catch (ArrayIndexOutOfBoundsException e){
System.out.println(e); }
System.out.println("other statement");
}
Nested try Example:
12/19/201726
}
catch(Exception e){
System.out.println("handled");
}
System.out.println("normal flow..");
}
} Output:
going to divide
java.lang.ArithmeticException: / by zero
java.lang.ArrayIndexOutOfBoundsException: 5
other statement
normal flow..
Finally block:
12/19/201727
 The finally block is a block that is always
executed.
 Before terminating the program, JVM executes
finally block(if any).
 Finally must be followed by try or catch block.
 finally block can be used to put "cleanup" code
such as closing a file, closing db connection
etc..,
finally Example:
12/19/201728
public class Main2{
public static void main(String args[]){
try {
int data=25/0;
System.out.println(data);
}
catch (NullPointerException e){System.out.println(e);}
finally {
System.out.println("finally block is always executed"); }
System.out.println("rest of the code...");
}
}
Output:
Exception in thread "main" finally block is always
executed
java.lang.ArithmeticException: / by zero
at Main2.main(Main2.java:4)
12/19/201729
Thank You

More Related Content

What's hot

Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
ARAFAT ISLAM
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Exception handling
Exception handlingException handling
Exception handling
Pranali Chaudhari
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
Nahian Ahmed
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Lovely Professional University
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
Google
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
pooja kumari
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
sharqiyem
 
Exception handling
Exception handling Exception handling
Exception handling
M Vishnuvardhan Reddy
 
Java Collections
Java  Collections Java  Collections

What's hot (20)

Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Presentation on-exception-handling
Presentation on-exception-handlingPresentation on-exception-handling
Presentation on-exception-handling
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
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
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Exception handling
Exception handling Exception handling
Exception handling
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Java Collections
Java  Collections Java  Collections
Java Collections
 

Similar to Exception handling

Exception handling
Exception handlingException handling
Exception handling
priyaankasrivastavaa
 
Exception handling
Exception handlingException handling
Exception handling
SAIFUR RAHMAN
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
rohitgudasi18
 
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handling
Abishek Purushothaman
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
ushakiranv110
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
AmbigaMurugesan
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
saman Iftikhar
 
Exception Handling
Exception HandlingException Handling
Exception Handlingbackdoor
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
yugandhar vadlamudi
 
Exceptions
ExceptionsExceptions
Exceptions
Soham Sengupta
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
Narayana Swamy
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
gopalrajput11
 
Exception Handling
Exception HandlingException Handling
Exception Handling
Ferdin Joe John Joseph PhD
 

Similar to Exception handling (20)

Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java unit3
Java unit3Java unit3
Java unit3
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
Multiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handlingMultiple Choice Questions for Java interfaces and exception handling
Multiple Choice Questions for Java interfaces and exception handling
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exceptions
ExceptionsExceptions
Exceptions
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
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
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 

More from PhD Research Scholar

Ajax
AjaxAjax
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
PhD Research Scholar
 
Quiz
QuizQuiz
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
PhD Research Scholar
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
PhD Research Scholar
 
1.java script
1.java script1.java script
1.java script
PhD Research Scholar
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
PhD Research Scholar
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
PhD Research Scholar
 
String
StringString
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io
PhD Research Scholar
 
Packages
PackagesPackages
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 
Inheritance
InheritanceInheritance
Applets
AppletsApplets
Abstract class
Abstract classAbstract class
Abstract class
PhD Research Scholar
 
7. tuples, set &amp; dictionary
7. tuples, set &amp; dictionary7. tuples, set &amp; dictionary
7. tuples, set &amp; dictionary
PhD Research Scholar
 
6. list
6. list6. list
5. string
5. string5. string
4. functions
4. functions4. functions
4. functions
PhD Research Scholar
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
PhD Research Scholar
 

More from PhD Research Scholar (20)

Ajax
AjaxAjax
Ajax
 
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
 
Quiz
QuizQuiz
Quiz
 
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
 
1.java script
1.java script1.java script
1.java script
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
 
String
StringString
String
 
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io
 
Packages
PackagesPackages
Packages
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Applets
AppletsApplets
Applets
 
Abstract class
Abstract classAbstract class
Abstract class
 
7. tuples, set &amp; dictionary
7. tuples, set &amp; dictionary7. tuples, set &amp; dictionary
7. tuples, set &amp; dictionary
 
6. list
6. list6. list
6. list
 
5. string
5. string5. string
5. string
 
4. functions
4. functions4. functions
4. functions
 
3.2 looping statement
3.2 looping statement3.2 looping statement
3.2 looping statement
 

Recently uploaded

MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
scholarhattraining
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
Priyankaranawat4
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
Bisnar Chase Personal Injury Attorneys
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptxFresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
SriSurya50
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
David Douglas School District
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
AyyanKhan40
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 

Recently uploaded (20)

MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
clinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdfclinical examination of hip joint (1).pdf
clinical examination of hip joint (1).pdf
 
Top five deadliest dog breeds in America
Top five deadliest dog breeds in AmericaTop five deadliest dog breeds in America
Top five deadliest dog breeds in America
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptxFresher’s Quiz 2023 at GMC Nizamabad.pptx
Fresher’s Quiz 2023 at GMC Nizamabad.pptx
 
Pride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School DistrictPride Month Slides 2024 David Douglas School District
Pride Month Slides 2024 David Douglas School District
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
PIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf IslamabadPIMS Job Advertisement 2024.pdf Islamabad
PIMS Job Advertisement 2024.pdf Islamabad
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 

Exception handling

  • 1. - Arulkumar V Assistant Professor, SECE Exception Handling
  • 2. Guess the Output: 12/19/20172 public class Arithmetic { public static void main(String[] Geek) { Integer a = 2; Integer b; b = a / 0; System.out.println("Value of b is:" +b); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at Arithmatic.main(Arithmatic.java:7)
  • 3. Introduction 12/19/20173  An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error.  In Java it is handled using 5 keywords try catch throw throws finally
  • 4. Using Keywords: 12/19/20174 try – A block of source code that is to be monitored for exception catch – It handles the specific type of exception along with the try block. throw – It is used to throw specific exception from the program code. throws – It specifies the exception that can be thrown by a particular method. finally – it specifies the code that must be executed even though exception may or may not be occur Note: 1. For ever try block there exist the cache block.
  • 5. Handling try-cache block: 12/19/20175 try block Exception object gets created here Throws Exception catch block Object Exception handler Exception causing statements Exception Handling statements
  • 6. Cont.., 12/19/20176  The statement(s) that are likely to cause an exception are enclosed within a try block. For these statements the exception is thrown.  There is another block defined by the keyword catch which is responsible for handling the exception thrown by the try catch block.  As soon as exception occurs it is handled by the catch block.  The cache block is added immediately after the try block
  • 7. Syntax of try- cache: 12/19/20177 try { //exception gets generated here } Catch(Type_of_Exception e) { //exception is handled here }
  • 8. Guess the Output: 12/19/20178 public class Arithmetic { public static void main(String[] Geek) { Integer a = 2; Integer b; try { b = a / 0; } catch (ArithmeticException e) { System.out.println(e + "Exception occurs"); } System.out.println("Exception Example Program"); } Output: java.lang.ArithmeticException: / by zeroException occurs Exception Example Program
  • 9. Hierarchy of Exception classes 12/19/20179
  • 10. Error 12/19/201710  Error is irrecoverable  e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
  • 11. throw keyword: 12/19/201711  It is used to explicitly throw an exception.  We can throw either checked or unchecked exception.  The throw keyword is mainly used to throw custom exception.
  • 12. throws keyword: 12/19/201712  If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception.  You do this by including a throws clause in the method’s declaration.  A throws clause lists the types of exceptions that a method might throw.
  • 13. throws keyword: 12/19/201713  This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses.  All other exceptions that a method can throw must be declared in the throws clause.  If they are not, a compile-time error will result
  • 14. throws Syntax: 12/19/201714 type method-name(parameter-list) throws exception-list { // body of method } Eg: static void validate (int age) throws InvalidAgeException
  • 15. throw & throws Example: 12/19/201715 class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super (s); System.out.println(s); } } public class ExceptionDemo { static void validate (int age) throws InvalidAgeException { if (age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); }
  • 16. throw Example: 12/19/201716 public static void main (String args[]){ try{ validate(13); } catch (Exception m){ System.out.println("Exception occurred: "+m); } System.out.println("rest of the code..."); } } Output: not valid Exception occurred: InvalidAgeException: not valid rest of the code...
  • 17. Difference between throw and throws keyword: 12/19/201717 Sl. No throw throws 1 It is used to explicitly throw an exception Used to declare and exception 2 It is followed by an instance It is followed by class 3 throw is used within the method. throws is used with the method signature. 4 You cannot throw multiple exception You can declare multiple exception e.g. public void method()throws IOException,SQLException.
  • 18. Uncaught Exception 12/19/201718  If there exist some code in the source program which may cause an exception and if the programmer does not handle this exception then java runtime system raises the exception.
  • 19. Uncaught Exception Example: 12/19/201719 public class Arithmetic { public static void main(String[] Geek) { Integer a = 2; Integer b; b = a / 0; System.out.println("Value of b is:" +b); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at Arithmatic.main(Arithmatic.java:7)
  • 20. Multiple catch block: 12/19/201720  If you have to perform different tasks at the occurrence of different Exceptions, use multiple catch block.  Note:  At a time only one Exception is occurred 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.
  • 21. Multiple catch block Example 1: 12/19/201721 public class Main1{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(ArithmeticException e){ System.out.println(e+" - task1 is completed"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("task 2 completed"); } catch(Exception e){ System.out.println("common task completed"); } System.out.println("rest of the code..."); } } Output: Task1 is completed rest of the code…
  • 22. Multiple catch block Example2: 12/19/201722 public class Main1{ public static void main(String args[]){ try{ int a[]=new int[5]; a[5]=30/0; } catch(Exception e){ System.out.println("common task completed"); } catch(ArithmeticException e){ System.out.println(e+" - task1 is completed"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("task 2 completed"); } System.out.println("rest of the code..."); } } Output: Compile-time error
  • 23. Nested try block: 12/19/201723  try block within a try block is known as nested try block.  Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error.  In such cases, exception handlers have to be nested
  • 24. Syntax of nested try block: 12/19/201724 try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } } catch(Exception e) { }
  • 25. Nested try Example: 12/19/201725 public class Main2{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; } catch (ArithmeticException e){ System.out.println(e); } try{ int a[]=new int[5]; a[5]=4; } catch (ArrayIndexOutOfBoundsException e){ System.out.println(e); } System.out.println("other statement"); }
  • 26. Nested try Example: 12/19/201726 } catch(Exception e){ System.out.println("handled"); } System.out.println("normal flow.."); } } Output: going to divide java.lang.ArithmeticException: / by zero java.lang.ArrayIndexOutOfBoundsException: 5 other statement normal flow..
  • 27. Finally block: 12/19/201727  The finally block is a block that is always executed.  Before terminating the program, JVM executes finally block(if any).  Finally must be followed by try or catch block.  finally block can be used to put "cleanup" code such as closing a file, closing db connection etc..,
  • 28. finally Example: 12/19/201728 public class Main2{ public static void main(String args[]){ try { int data=25/0; System.out.println(data); } catch (NullPointerException e){System.out.println(e);} finally { System.out.println("finally block is always executed"); } System.out.println("rest of the code..."); } } Output: Exception in thread "main" finally block is always executed java.lang.ArithmeticException: / by zero at Main2.main(Main2.java:4)