SlideShare a Scribd company logo
1 of 17
 
NARAINA COLLEGE OF ENGINEERING & 
TECHNOLOGY 
 UPTU CODE-287 
 
 PRESENTED BY 
 Priyanka Srivastava 
 I.T.-4th year 
 7th Semester
 What is error 
 What is exception 
 Exception handling 
 Try,catch n finally block 
 Use of throws
Java Exception Type Hierarchy 
1) virtual machine errors 
2) 
3) everything else
An Error is any unexpected result obtained 
from a program during execution. 
Error cann’t handle by the programmer 
Some typical causes of errors: 
Memory errors (i.e. memory incorrectly 
allocated, memory leaks, “null pointer”) 
File system errors (i.e. disk is full, disk has 
been removed) 
Network errors (i.e. network is down)
 It is the problem that arise during the 
exection of a program. 
 The exception class is as subclass of 
throwable class. 
 Other than the exception class there is 
another sub class which is derived from 
throwable class
 Exception handling in java is managed 
through five keywords – 
1. Try 
2. Catch 
3. Finally 
4. Throws 
5. Throw
 Unchecked Exceptions 
It is not required that these 
types of exceptions be caught or 
declared on a method. 
 Runtime exceptions can be 
generated by methods or by 
the JVM itself. 
 Errors are generated from 
deep within the JVM, and 
often indicate a truly fatal 
state. 
 Runtime exceptions are a 
source of major controversy! 
 Checked Exceptions 
Must either be caught by a 
method or declared in its 
signature. 
 Placing exceptions in the 
method signature harkens 
back to a major concern for 
Goodenough. 
 This requirement is viewed 
with derision in the hardcore 
C++ community. 
 A common technique for 
simplifying checked 
exceptions is subsumption. 
Copyright (c) 2001 DeLorme 7
 Example 
 try { 
… normal program code 
} 
catch(Exception e) { 
… exception handling code 
}
import java.io.*; 
public class demo 
{ 
public static void main(String[] args) 
{ 
try 
{ 
int a,b,c; 
a=5; 
b=0; 
c=a/b; 
System.out.println(c); 
} 
catch(ArithmeticException ae) 
{ 
System.out.println("hello"); 
System.out.println(ae); 
} 
}}
import java.io.*; 
public class ExcepTest{ 
public static void main(String args[]){ 
try{ 
int a[] = new int[2]; 
System.out.println("Access element 
three :" + a[3]); 
}catch(ArrayIndexOutOfBoundsException 
e){ 
System.out.println("Exception thrown 
:" + e); 
} 
System.out.println("Out of the block"); 
} 
} 
This would produce following result: 
Exception thrown 
:java.lang.ArrayIndexOutOfBoundsExceptio 
n: 3 
Out of the block
 A try block can be followed by multiple catch blocks. The syntax for 
multiple catch blocks looks like the following: 
 try 
 { 
 //Protected code 
 }catch(ExceptionType1 e1) 
 { 
 //Catch block 
 }catch(ExceptionType2 e2) 
 { 
 //Catch block 
 }catch(ExceptionType3 e3) 
 { 
 //Catch block 
 }
 When an error condition is detected, it is necessary to handle it immediately where 
detected or throw the exception to the calling method. 
 Exception handling is a mechanism for transferring control from where an error 
occurred to where it can be handled most appropriately. 
 After the exception is thrown, the throwing method terminates and execution 
control is immediately passed backward along the chain of callers from where the 
exception was thrown. 
 Any method along the calling chain can: 
a) handle the exception and continue with execution, 
b) handle the exception and again throw the exception to the calling method to 
handle 
c) or do nothing, terminate immediately and let the calling method deal with the 
exception. 
 The down method below is an example of throwing an exception, in this case when 
the counter n becomes 
12
13 
public int down() throws counterException { 
if (n <= 0) 
throw new counterException( 
n + " count Down failed."); 
return --n; 
} 
•The down method is an example of throwing an exception, in this case when the 
counter n becomes negative. 
•If exception is thrown, execution does not reach return --n;
/* The IllegalArgumentException is considered unchecked, and 
* even making it part of the signature will not alter that. */ 
public void setName(String p_strName) throws IllegalArgumentException 
{ 
/* valid names cannot be zero length */ 
if (p_strName.length() == 0) { 
throw new IllegalArgumentException(“…”); 
} 
m_strName = p_strName; 
} 
public void foo() { 
setName(“”); /* No warning about unhandled exceptions. */ 
} 
Copyright (c) 2001 DeLorme 14
public bool anotherMethod(Object myParameter) { 
try { /* What value does this snippet return? */ 
myClass.myMethod(myParameter); 
return true; 
} catch (Exception e) { 
System.err.println(“Exception in anotherMethod() “+e.toString()); 
return false; 
} finally { 
/* If the close operation can raise an exception, whoops! */ 
if (myClass.close() == false) { 
break; 
} 
} 
return false; 
} 
Copyright (c) 2001 DeLorme 15
 Exceptions are a powerful error handling 
mechanism. 
 Exceptions in Java are built into the language. 
 Exceptions can be handled by the 
programmer (try-catch), or handled by the 
Java environment (throws).
Java Exception Handling Concepts Explained

More Related Content

What's hot

130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15Kumar
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++Jayant Dalvi
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]ppd1961
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Janki Shah
 
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 javagopalrajput11
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in cMemo Yekem
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 

What's hot (20)

130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
C++ ala
C++ alaC++ ala
C++ ala
 
Exception handling chapter15
Exception handling chapter15Exception handling chapter15
Exception handling chapter15
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
What is Exception Handling?
What is Exception Handling?What is Exception Handling?
What is Exception Handling?
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++Exception Handling in object oriented programming using C++
Exception Handling in object oriented programming using C++
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Presentation1
Presentation1Presentation1
Presentation1
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in c
Exception handling in cException handling in c
Exception handling in c
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 

Viewers also liked

Presentation 10 15 v1
Presentation 10 15 v1Presentation 10 15 v1
Presentation 10 15 v1Alicia White
 
Assessing web site usability measurement
Assessing web site usability measurementAssessing web site usability measurement
Assessing web site usability measurementeSAT Publishing House
 
Software cost estimation
Software cost estimationSoftware cost estimation
Software cost estimationdeep sharma
 
Training module engine (4)
Training module engine (4)Training module engine (4)
Training module engine (4)ashutosh dash
 
Spain 1st day powerpoint
Spain 1st day powerpointSpain 1st day powerpoint
Spain 1st day powerpointShafonda Spain
 
201411 141204212906-conversion-gate01
201411 141204212906-conversion-gate01201411 141204212906-conversion-gate01
201411 141204212906-conversion-gate01cct-inc
 
Howtousestockphotosandstilllookcool
Howtousestockphotosandstilllookcool Howtousestockphotosandstilllookcool
Howtousestockphotosandstilllookcool Manoore Birhan
 
Data research portal
Data research portal Data research portal
Data research portal sudeepsakalle
 

Viewers also liked (10)

Presentation 10 15 v1
Presentation 10 15 v1Presentation 10 15 v1
Presentation 10 15 v1
 
Assessing web site usability measurement
Assessing web site usability measurementAssessing web site usability measurement
Assessing web site usability measurement
 
Blog 2
Blog 2Blog 2
Blog 2
 
Software cost estimation
Software cost estimationSoftware cost estimation
Software cost estimation
 
Training module engine (4)
Training module engine (4)Training module engine (4)
Training module engine (4)
 
Spain 1st day powerpoint
Spain 1st day powerpointSpain 1st day powerpoint
Spain 1st day powerpoint
 
THE EGYPT-A Pharaoh Country
THE EGYPT-A Pharaoh CountryTHE EGYPT-A Pharaoh Country
THE EGYPT-A Pharaoh Country
 
201411 141204212906-conversion-gate01
201411 141204212906-conversion-gate01201411 141204212906-conversion-gate01
201411 141204212906-conversion-gate01
 
Howtousestockphotosandstilllookcool
Howtousestockphotosandstilllookcool Howtousestockphotosandstilllookcool
Howtousestockphotosandstilllookcool
 
Data research portal
Data research portal Data research portal
Data research portal
 

Similar to Java Exception Handling Concepts Explained

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 developmentrohitgudasi18
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling Intro C# Book
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming languageushakiranv110
 
Exception Handling
Exception HandlingException Handling
Exception HandlingSunil OS
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threadsDevaKumari Vijay
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 

Similar to Java Exception Handling Concepts Explained (20)

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
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
17 exceptions
17   exceptions17   exceptions
17 exceptions
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
12. Exception Handling
12. Exception Handling 12. Exception Handling
12. Exception Handling
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception Hnadling java programming language
Exception Hnadling  java programming languageException Hnadling  java programming language
Exception Hnadling java programming language
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 

Recently uploaded

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 

Recently uploaded (20)

Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Java Exception Handling Concepts Explained

  • 1.  NARAINA COLLEGE OF ENGINEERING & TECHNOLOGY  UPTU CODE-287   PRESENTED BY  Priyanka Srivastava  I.T.-4th year  7th Semester
  • 2.  What is error  What is exception  Exception handling  Try,catch n finally block  Use of throws
  • 3. Java Exception Type Hierarchy 1) virtual machine errors 2) 3) everything else
  • 4. An Error is any unexpected result obtained from a program during execution. Error cann’t handle by the programmer Some typical causes of errors: Memory errors (i.e. memory incorrectly allocated, memory leaks, “null pointer”) File system errors (i.e. disk is full, disk has been removed) Network errors (i.e. network is down)
  • 5.  It is the problem that arise during the exection of a program.  The exception class is as subclass of throwable class.  Other than the exception class there is another sub class which is derived from throwable class
  • 6.  Exception handling in java is managed through five keywords – 1. Try 2. Catch 3. Finally 4. Throws 5. Throw
  • 7.  Unchecked Exceptions It is not required that these types of exceptions be caught or declared on a method.  Runtime exceptions can be generated by methods or by the JVM itself.  Errors are generated from deep within the JVM, and often indicate a truly fatal state.  Runtime exceptions are a source of major controversy!  Checked Exceptions Must either be caught by a method or declared in its signature.  Placing exceptions in the method signature harkens back to a major concern for Goodenough.  This requirement is viewed with derision in the hardcore C++ community.  A common technique for simplifying checked exceptions is subsumption. Copyright (c) 2001 DeLorme 7
  • 8.  Example  try { … normal program code } catch(Exception e) { … exception handling code }
  • 9. import java.io.*; public class demo { public static void main(String[] args) { try { int a,b,c; a=5; b=0; c=a/b; System.out.println(c); } catch(ArithmeticException ae) { System.out.println("hello"); System.out.println(ae); } }}
  • 10. import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsExceptio n: 3 Out of the block
  • 11.  A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:  try  {  //Protected code  }catch(ExceptionType1 e1)  {  //Catch block  }catch(ExceptionType2 e2)  {  //Catch block  }catch(ExceptionType3 e3)  {  //Catch block  }
  • 12.  When an error condition is detected, it is necessary to handle it immediately where detected or throw the exception to the calling method.  Exception handling is a mechanism for transferring control from where an error occurred to where it can be handled most appropriately.  After the exception is thrown, the throwing method terminates and execution control is immediately passed backward along the chain of callers from where the exception was thrown.  Any method along the calling chain can: a) handle the exception and continue with execution, b) handle the exception and again throw the exception to the calling method to handle c) or do nothing, terminate immediately and let the calling method deal with the exception.  The down method below is an example of throwing an exception, in this case when the counter n becomes 12
  • 13. 13 public int down() throws counterException { if (n <= 0) throw new counterException( n + " count Down failed."); return --n; } •The down method is an example of throwing an exception, in this case when the counter n becomes negative. •If exception is thrown, execution does not reach return --n;
  • 14. /* The IllegalArgumentException is considered unchecked, and * even making it part of the signature will not alter that. */ public void setName(String p_strName) throws IllegalArgumentException { /* valid names cannot be zero length */ if (p_strName.length() == 0) { throw new IllegalArgumentException(“…”); } m_strName = p_strName; } public void foo() { setName(“”); /* No warning about unhandled exceptions. */ } Copyright (c) 2001 DeLorme 14
  • 15. public bool anotherMethod(Object myParameter) { try { /* What value does this snippet return? */ myClass.myMethod(myParameter); return true; } catch (Exception e) { System.err.println(“Exception in anotherMethod() “+e.toString()); return false; } finally { /* If the close operation can raise an exception, whoops! */ if (myClass.close() == false) { break; } } return false; } Copyright (c) 2001 DeLorme 15
  • 16.  Exceptions are a powerful error handling mechanism.  Exceptions in Java are built into the language.  Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws).