SlideShare a Scribd company logo
Exception Handling in Java
Objectives
• Introduction
• What exceptions are for
• Catching & Throwing exceptions
• Exception Specifications
• Standard Java Exceptions
• Exceptions and Polymorphism
• The finally clause
• Resource Management
• Uncaught Exceptions
Introduction
• Due to design errors or coding errors, our
programs may fail in unexpected ways during
execution. An exception is a condition that is
caused by run time error in the program. The
purpose of the exception handling mechanism
is to provide a means to detect and report an
“ecxceptional circumstances” .
Error
• An error may produce an incorrect output or
may terminate the execution of the program
abruptly or even may cause the system to
crash. So it is our responsibility to detect and
manage the error properly.
Types of error
• Runtime Errors: occur while the program is
running if the environment detects an
operation that is impossible to carry out.
• Logic Errors: occur when a program doesn't
perform the way it was intended
• Syntax Errors: Arise because the rules of the
language have not been followed. They are
detected by the compiler.
Example of Run Time error
Class Error
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=5;
int x=a/(b+c);
System.out.println("x=" +x);
int y=a/(b-c); // Errorr division by zero
System.out.println("y=" +y);
}
}
Errors and Error Handling
• 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, URL does
not exist)
– Calculation errors (i.e. divide by 0)
Errors and Error Handling
• More typical causes of errors:
– Array errors (i.e. accessing element –1)
– Conversion errors (i.e. convert ‘q’ to a number)
– Can you think of some others?
Errors and Error Handling
• Exceptions – a better error handling
– Exceptions are a mechanism that provides the
best of both worlds.
– Exceptions act similar to method return flags in
that any method may raise and exception should it
encounter an error.
– Exceptions act like global error methods in that
the exception mechanism is built into Java;
exceptions are handled at many levels in a
program, locally and/or globally.
Exceptions
• How do you handle exceptions?
– To handle the exception, you write a “try-catch”
block. To pass the exception “up the chain”, you
declare a throws clause in your method or class
declaration.
– If the method contains code that may cause a
checked exception, you MUST handle the
exception OR pass the exception to the parent
class (remember, every class has Object as the
ultimate parent)
Coding Exceptions
• Coding Exceptions
• Try-Catch Mechanism
– Wherever your code may trigger an exception, the
normal code logic is placed inside a block of code
starting with the “try” keyword:
– After the try block, the code to handle the
exception should it arise is placed in a block of
code starting with the “catch” keyword.
Standard Java Exceptions
Throwable
Exception Error
Runtime
Exception
IO Exception
Catching Exceptions
• Wrap code to be checked in a try-block
– checking occurs all the way down the execution
stack
• try-blocks can be nested
– control resumes at most enclosed matching
handler
Coding Exceptions
• Example
– try {
… normal program code
}
catch(Exception e) {
… exception handling code
}
Coding Exceptions
• Types of Exceptions
– Examples:
• public void myMethod throws Exception {
• public void myMethod throws IOException {
• try { … }
catch (Exception e) { … }
• try { … }
catch (IOException ioe) { … }
Code Examples
• 1. Demonstration of an unchecked exception
(NullPointerException)
• 2. Demonstration of checked exceptions:
– Passing a DivideByZeroException
– Handling a DivideByZeroException
Example
class error2
{
public static void main(String arg[])
{
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println(“Division by Zero”);
}
Y=a/(b-c);
System.out.println(“y=“+y);
}
}
In the previous program we cannot see the
value of x just because of the error in the
value of y, that is division by zero but when we
use the try and catch blocks in exception
handling then we can see the value of y which
is correct and our program will display an
error message shown in the try block.
conclusion
– 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).
– Exception handling can only hide the errors.
– It cannot correct the errors.

More Related Content

Similar to exception-handling-in-java.ppt unit 2

Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
FacultyAnupamaAlagan
 
Exception handling
Exception handlingException handling
Exception handling
Abhishek Pachisia
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
SanthiNivas
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
Kunal Singh
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Design byexceptions
Design byexceptionsDesign byexceptions
Design byexceptionsAsif Tasleem
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
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
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
teach4uin
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
Ankit Rai
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
Ashfaaq Mahroof
 

Similar to exception-handling-in-java.ppt unit 2 (20)

Exception handling
Exception handlingException handling
Exception handling
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
Exception handling
Exception handlingException handling
Exception handling
 
exception-handling-in-java.ppt
exception-handling-in-java.pptexception-handling-in-java.ppt
exception-handling-in-java.ppt
 
Exception handling in JAVA
Exception handling in JAVAException handling in JAVA
Exception handling in JAVA
 
Um presentation (1)
Um presentation (1)Um presentation (1)
Um presentation (1)
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Design byexceptions
Design byexceptionsDesign byexceptions
Design byexceptions
 
Exception handling
Exception handlingException handling
Exception handling
 
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
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 

More from thenmozhip8

U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
thenmozhip8
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdf
thenmozhip8
 
unit 3 ppt.pptx
unit 3 ppt.pptxunit 3 ppt.pptx
unit 3 ppt.pptx
thenmozhip8
 
Unit 1 .ppt
Unit 1 .pptUnit 1 .ppt
Unit 1 .ppt
thenmozhip8
 
IR UNIT V.docx
IR UNIT  V.docxIR UNIT  V.docx
IR UNIT V.docx
thenmozhip8
 
IRT Unit_4.pptx
IRT Unit_4.pptxIRT Unit_4.pptx
IRT Unit_4.pptx
thenmozhip8
 
UNIT 3 IRT.docx
UNIT 3 IRT.docxUNIT 3 IRT.docx
UNIT 3 IRT.docx
thenmozhip8
 
IRT Unit_ 2.pptx
IRT Unit_ 2.pptxIRT Unit_ 2.pptx
IRT Unit_ 2.pptx
thenmozhip8
 
IRT Unit_I.pptx
IRT Unit_I.pptxIRT Unit_I.pptx
IRT Unit_I.pptx
thenmozhip8
 
packages unit 5 .ppt
packages  unit 5 .pptpackages  unit 5 .ppt
packages unit 5 .ppt
thenmozhip8
 
unit 4 .ppt
unit 4 .pptunit 4 .ppt
unit 4 .ppt
thenmozhip8
 
Definning class.pptx unit 3
Definning class.pptx unit 3Definning class.pptx unit 3
Definning class.pptx unit 3
thenmozhip8
 
unit 1 full ppt.pptx
unit 1 full ppt.pptxunit 1 full ppt.pptx
unit 1 full ppt.pptx
thenmozhip8
 

More from thenmozhip8 (14)

U5 SPC.pptx
U5 SPC.pptxU5 SPC.pptx
U5 SPC.pptx
 
Unit 4.pdf
Unit 4.pdfUnit 4.pdf
Unit 4.pdf
 
unit 3 ppt.pptx
unit 3 ppt.pptxunit 3 ppt.pptx
unit 3 ppt.pptx
 
U2.ppt
U2.pptU2.ppt
U2.ppt
 
Unit 1 .ppt
Unit 1 .pptUnit 1 .ppt
Unit 1 .ppt
 
IR UNIT V.docx
IR UNIT  V.docxIR UNIT  V.docx
IR UNIT V.docx
 
IRT Unit_4.pptx
IRT Unit_4.pptxIRT Unit_4.pptx
IRT Unit_4.pptx
 
UNIT 3 IRT.docx
UNIT 3 IRT.docxUNIT 3 IRT.docx
UNIT 3 IRT.docx
 
IRT Unit_ 2.pptx
IRT Unit_ 2.pptxIRT Unit_ 2.pptx
IRT Unit_ 2.pptx
 
IRT Unit_I.pptx
IRT Unit_I.pptxIRT Unit_I.pptx
IRT Unit_I.pptx
 
packages unit 5 .ppt
packages  unit 5 .pptpackages  unit 5 .ppt
packages unit 5 .ppt
 
unit 4 .ppt
unit 4 .pptunit 4 .ppt
unit 4 .ppt
 
Definning class.pptx unit 3
Definning class.pptx unit 3Definning class.pptx unit 3
Definning class.pptx unit 3
 
unit 1 full ppt.pptx
unit 1 full ppt.pptxunit 1 full ppt.pptx
unit 1 full ppt.pptx
 

Recently uploaded

AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Teleport Manpower Consultant
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
gestioneergodomus
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
gdsczhcet
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
obonagu
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
ssuser7dcef0
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
VENKATESHvenky89705
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
AmarGB2
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 

Recently uploaded (20)

AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdfTop 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
Top 10 Oil and Gas Projects in Saudi Arabia 2024.pdf
 
DfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributionsDfMAy 2024 - key insights and contributions
DfMAy 2024 - key insights and contributions
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Gen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdfGen AI Study Jams _ For the GDSC Leads in India.pdf
Gen AI Study Jams _ For the GDSC Leads in India.pdf
 
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
在线办理(ANU毕业证书)澳洲国立大学毕业证录取通知书一模一样
 
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
NUMERICAL SIMULATIONS OF HEAT AND MASS TRANSFER IN CONDENSING HEAT EXCHANGERS...
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
road safety engineering r s e unit 3.pdf
road safety engineering  r s e unit 3.pdfroad safety engineering  r s e unit 3.pdf
road safety engineering r s e unit 3.pdf
 
Investor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptxInvestor-Presentation-Q1FY2024 investor presentation document.pptx
Investor-Presentation-Q1FY2024 investor presentation document.pptx
 
Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 

exception-handling-in-java.ppt unit 2

  • 2. Objectives • Introduction • What exceptions are for • Catching & Throwing exceptions • Exception Specifications • Standard Java Exceptions • Exceptions and Polymorphism • The finally clause • Resource Management • Uncaught Exceptions
  • 3. Introduction • Due to design errors or coding errors, our programs may fail in unexpected ways during execution. An exception is a condition that is caused by run time error in the program. The purpose of the exception handling mechanism is to provide a means to detect and report an “ecxceptional circumstances” .
  • 4. Error • An error may produce an incorrect output or may terminate the execution of the program abruptly or even may cause the system to crash. So it is our responsibility to detect and manage the error properly.
  • 5. Types of error • Runtime Errors: occur while the program is running if the environment detects an operation that is impossible to carry out. • Logic Errors: occur when a program doesn't perform the way it was intended • Syntax Errors: Arise because the rules of the language have not been followed. They are detected by the compiler.
  • 6. Example of Run Time error Class Error { public static void main(String args[]) { int a=10; int b=5; int c=5; int x=a/(b+c); System.out.println("x=" +x); int y=a/(b-c); // Errorr division by zero System.out.println("y=" +y); } }
  • 7. Errors and Error Handling • 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, URL does not exist) – Calculation errors (i.e. divide by 0)
  • 8. Errors and Error Handling • More typical causes of errors: – Array errors (i.e. accessing element –1) – Conversion errors (i.e. convert ‘q’ to a number) – Can you think of some others?
  • 9. Errors and Error Handling • Exceptions – a better error handling – Exceptions are a mechanism that provides the best of both worlds. – Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. – Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.
  • 10. Exceptions • How do you handle exceptions? – To handle the exception, you write a “try-catch” block. To pass the exception “up the chain”, you declare a throws clause in your method or class declaration. – If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class (remember, every class has Object as the ultimate parent)
  • 11. Coding Exceptions • Coding Exceptions • Try-Catch Mechanism – Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the “try” keyword: – After the try block, the code to handle the exception should it arise is placed in a block of code starting with the “catch” keyword.
  • 12. Standard Java Exceptions Throwable Exception Error Runtime Exception IO Exception
  • 13. Catching Exceptions • Wrap code to be checked in a try-block – checking occurs all the way down the execution stack • try-blocks can be nested – control resumes at most enclosed matching handler
  • 14. Coding Exceptions • Example – try { … normal program code } catch(Exception e) { … exception handling code }
  • 15. Coding Exceptions • Types of Exceptions – Examples: • public void myMethod throws Exception { • public void myMethod throws IOException { • try { … } catch (Exception e) { … } • try { … } catch (IOException ioe) { … }
  • 16. Code Examples • 1. Demonstration of an unchecked exception (NullPointerException) • 2. Demonstration of checked exceptions: – Passing a DivideByZeroException – Handling a DivideByZeroException
  • 17. Example class error2 { public static void main(String arg[]) { int a=10; int b=5; int c=5; int x,y; try { x=a/(b-c); } catch(ArithmeticException e) { System.out.println(“Division by Zero”); } Y=a/(b-c); System.out.println(“y=“+y); } }
  • 18. In the previous program we cannot see the value of x just because of the error in the value of y, that is division by zero but when we use the try and catch blocks in exception handling then we can see the value of y which is correct and our program will display an error message shown in the try block.
  • 19. conclusion – 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). – Exception handling can only hide the errors. – It cannot correct the errors.