SlideShare une entreprise Scribd logo
1  sur  64
Module 8     Exceptions & Assertions
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Java method call stack
Exception propagation Imagine a building, say, five stories high, and at each floor there is a  deck or balcony. Now imagine that on each deck, one person is standing holding  a baseball mitt. Exceptions are like balls dropped from person to person, starting from  the roof. An exception is first thrown from the top of the stack (in other words,  the person on the roof)
If it isn't caught by the same person who threw it (the person on the  roof), it drops down the call stack to the previous method, which is the  person standing on the deck one floor down.  If not caught there, by the person one floor down, the  exception/ball again drops down to the previous method (person on  the next floor down), and so on until it is caught or until it reaches  the very bottom of the call stack. This is called  exception propagation. If an exception reaches the bottom of the call stack, it's like  reaching the bottom of a very long drop; the ball explodes, and so  does your program.
Throwing an Exception *  When an error occurs within a method, the method  creates an object and hands it off to the runtime  system. *  The object, called an  exception object , contains  information about the error, including its type  and the state of the program when the error occurred.  *  Creating an exception object and handing it to the  runtime system is called  throwing an exception .
After a method throws an exception, the runtime system attempts to find something to handle it.This "somethings" to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the  call stack. call stack
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Example  DodgeException.java
 
 
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Flow of simple exception conditions   Exception  try()  catch()   Behaviour No N/A N/A   Normal Flow   Yes No N/A   Method Termination   Yes Yes No   Compile Time Error   Yes Yes Yes   *Terminate try{} block   *Execute body of matching   Catch block   *Continue Normal flow after   Catch block
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
The throws statement 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.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Because the program does not specify a throws  clause to declare this  fact, the program will not compile. To make this example compile, you need to make two changes.  1. First, you need to declare that throwOne( ) throws  IllegalAccessException.  2. Second, main( ) must define a try/catch statement that catches  this exception.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Assertions   An  assertion  is a statement in the Java programming  language that enables you to test your assumptions about your  program.  Suppose you assume that a number passed into a method  will never be negative,to validate your assumption,you write private void methodA(int num) {   if (num >= 0) {   useNum(num + x); } else { // num must be < 0 // This code should never be reached! System.out.println(&quot;Yikes! num is a negative number! &quot; + num);} }
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Forms of Assertion The assertion statement has two forms.  The first, simpler form is:  assert  Expression1  ; where  Expression1  is a boolean expression. When the system runs  the assertion, it evaluates  Expression1  and if it is false throws  an AssertionError with no detail message.  Example private void doStuff() { assert (y > x); // more code assuming y is greater than x }
The second form of the assertion statement is:  assert  Expression1  :  Expression2  ;  where:  Expression1  is a boolean expression.  Expression2  is an expression that has a value.  The second form  assert  Expression1  :  Expression2  ;  Use this version of the assert statement to provide a detail message  for the AssertionError. The system passes the value of  Expression2  to the appropriate  AssertionError constructor, which uses the string representation of  the value as the error's detail message.
[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
It probably indicates an assumption that the suit variable will have  one of only four values. To test this assumption, add the following  default case:  default: assert false : suit;  If the suit variable takes on another value and assertions are enabled,  the assert will fail and an AssertionError will be thrown.  Alternative is: default: throw new AssertionError(suit);  This alternative offers protection even if assertions are disabled
Control-Flow Invariants Place an assertion at any location you assume will not be  reached.  The assertions statement to use is:  assert false;  For example, suppose you have a method that looks like this:  void foo() {  for (...) {  if (...)  return;  }  // Execution should never reach this point!!!   }
Replace the final comment so that the code now reads:  void foo() {  for (...) {  if (...) return;  }  assert false; // Execution should never reach this point!   }
Preconditions & Postconditions By convention, preconditions on  public  methods are enforced by  explicit checks that throw particular, specified exceptions.  For example:  public void setRefreshRate(int rate) {  //  Enforce specified precondition in public method   if (rate <= 0 || rate > MAX_REFRESH_RATE)  throw new IllegalArgumentException(&quot;Illegal rate: &quot; + rate);  setRefreshInterval(1000/rate);  } This convention is unaffected by the addition of the assert construct.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
However assertion can be used to test a  non public  method's  precondition. If you write a private method, you almost certainly wrote (or control)  any code that calls it.  When you assume that the logic in code calling your private  method is correct, you can test that assumption with an assertion  as follows: private void doMore(int x) { assert (x > 0); // do things with x } Remember  You're certainly free to compile assertion code with an inappropriate  validation of public arguments,
Don't Use assertions to validate Command-Line arguments If your program requires command-line arguments, you'll probably use the exception mechanism to enforce them.
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
If using a Java 1.4 compiler , and also using assert as a keyword  (in other words, you're actually trying to assert something in your  code), then you must explicitly enable assertion-awareness at  compile time, as follows: javac -source 1.4 com/geeksanonymous/TestClass.java The Java 5 compiler  will use the assert keyword by default, the compiler will generate an error message if it finds the word assert used as an identifier. However, you can tell the compiler that you're giving it an old piece of code to compile, javac -source 1.3 OldCode.java
What will happen in the following case Suppose the program is using the assert as an identifier and you  compile using  javac -source 1.4 NotQuiteSoOldCode.java Will the code compile?
In this case, the compiler will issue errors when it discovers the word  assert used as an identifier. Using Java 5 Compiler
Enable Assertions Programmers of certain critical systems might wish to ensure  that assertions are not disabled in the field.  The following static initialization idiom prevents a class from being  initialized if its assertions have been disabled: static {  boolean assertsEnabled = false;  assert assertsEnabled = true; // Intentional side effect!!!  if (!assertsEnabled)  throw new RuntimeException(&quot;Asserts must be enabled!!!&quot;);  }
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Selective Enabling and Disabling no arguments     Enables or disables assertions in all classes except system classes.  packageName ...     Enables or disables assertions in the named package and any  subpackages.  className    Enables or disables assertions in the named class
For example,   java -ea:com.wombat.fruitbat  BatTutor The following command runs a program, BatTutor,  with assertions enabled in only package com.wombat.fruitbat  and its subpackages:  -enablesystemassertions, or -esa.  To enable assertions in all system classes. java -ea -da:com.geeksanonymous.Foo this tells the JVM to enable assertions in general, but disable them in the class com.geeksanonymous.Foo. java -ea -da:com.geeksanonymous... tells the JVM to enable assertions in general, but disable  them in the package com.geeksanonymous, and all of its subpackages!

Contenu connexe

Tendances

Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaPratik Soares
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and AppletsTanmoy Roy
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handlingDeepak Sharma
 
Exceptionhandling
ExceptionhandlingExceptionhandling
ExceptionhandlingNuha Noor
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handlingraksharao
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapriyankazope
 
exception handling in java
exception handling in java exception handling in java
exception handling in java aptechsravan
 

Tendances (20)

Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling 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
 
Built in exceptions
Built in exceptions Built in exceptions
Built in exceptions
 
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
 
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
 
Java Exception Handling and Applets
Java Exception Handling and AppletsJava Exception Handling and Applets
Java Exception Handling and Applets
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
7.error management and exception handling
7.error management and exception handling7.error management and exception handling
7.error management and exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in java
Exception handling in java Exception handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handling Exception handling
Exception handling
 
exception handling in java
exception handling in java exception handling in java
exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 

Similaire à Md07 exceptions&assertion

Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handlingHemant Chetwani
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summaryEduardo Bergavera
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 

Similaire à Md07 exceptions&assertion (20)

Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Java exceptions
Java exceptionsJava exceptions
Java exceptions
 
130410107010 exception handling
130410107010 exception handling130410107010 exception handling
130410107010 exception handling
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Z blue exception
Z blue   exceptionZ blue   exception
Z blue exception
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
Chapter 8 - Exceptions and Assertions Edit summary
Chapter 8 - Exceptions and Assertions  Edit summaryChapter 8 - Exceptions and Assertions  Edit summary
Chapter 8 - Exceptions and Assertions Edit summary
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 

Plus de Rakesh Madugula

Plus de Rakesh Madugula (13)

New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
Md121 streams
Md121 streamsMd121 streams
Md121 streams
 
Md11 gui event handling
Md11 gui event handlingMd11 gui event handling
Md11 gui event handling
 
Md10 building java gu is
Md10 building java gu isMd10 building java gu is
Md10 building java gu is
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Md06 advance class features
Md06 advance class featuresMd06 advance class features
Md06 advance class features
 
Md05 arrays
Md05 arraysMd05 arrays
Md05 arrays
 
Md04 flow control
Md04 flow controlMd04 flow control
Md04 flow control
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
A begineers guide of JAVA - Getting Started
 A begineers guide of JAVA - Getting Started A begineers guide of JAVA - Getting Started
A begineers guide of JAVA - Getting Started
 

Dernier

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 

Dernier (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 

Md07 exceptions&assertion

  • 1. Module 8 Exceptions & Assertions
  • 2.
  • 3.
  • 4.
  • 6. Exception propagation Imagine a building, say, five stories high, and at each floor there is a deck or balcony. Now imagine that on each deck, one person is standing holding a baseball mitt. Exceptions are like balls dropped from person to person, starting from the roof. An exception is first thrown from the top of the stack (in other words, the person on the roof)
  • 7. If it isn't caught by the same person who threw it (the person on the roof), it drops down the call stack to the previous method, which is the person standing on the deck one floor down. If not caught there, by the person one floor down, the exception/ball again drops down to the previous method (person on the next floor down), and so on until it is caught or until it reaches the very bottom of the call stack. This is called exception propagation. If an exception reaches the bottom of the call stack, it's like reaching the bottom of a very long drop; the ball explodes, and so does your program.
  • 8. Throwing an Exception * When an error occurs within a method, the method creates an object and hands it off to the runtime system. * The object, called an exception object , contains information about the error, including its type and the state of the program when the error occurred. * Creating an exception object and handing it to the runtime system is called throwing an exception .
  • 9. After a method throws an exception, the runtime system attempts to find something to handle it.This &quot;somethings&quot; to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The list of methods is known as the call stack. call stack
  • 10.
  • 12.  
  • 13.  
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27. Flow of simple exception conditions   Exception try() catch() Behaviour No N/A N/A Normal Flow   Yes No N/A Method Termination   Yes Yes No Compile Time Error   Yes Yes Yes *Terminate try{} block *Execute body of matching Catch block *Continue Normal flow after Catch block
  • 28.
  • 29.
  • 30. The throws statement 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.
  • 31.
  • 32. Because the program does not specify a throws clause to declare this fact, the program will not compile. To make this example compile, you need to make two changes. 1. First, you need to declare that throwOne( ) throws IllegalAccessException. 2. Second, main( ) must define a try/catch statement that catches this exception.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41. Assertions An assertion is a statement in the Java programming language that enables you to test your assumptions about your program. Suppose you assume that a number passed into a method will never be negative,to validate your assumption,you write private void methodA(int num) { if (num >= 0) { useNum(num + x); } else { // num must be < 0 // This code should never be reached! System.out.println(&quot;Yikes! num is a negative number! &quot; + num);} }
  • 42.
  • 43. Forms of Assertion The assertion statement has two forms. The first, simpler form is: assert Expression1 ; where Expression1 is a boolean expression. When the system runs the assertion, it evaluates Expression1 and if it is false throws an AssertionError with no detail message. Example private void doStuff() { assert (y > x); // more code assuming y is greater than x }
  • 44. The second form of the assertion statement is: assert Expression1 : Expression2 ; where: Expression1 is a boolean expression. Expression2 is an expression that has a value. The second form assert Expression1 : Expression2 ; Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50. It probably indicates an assumption that the suit variable will have one of only four values. To test this assumption, add the following default case: default: assert false : suit; If the suit variable takes on another value and assertions are enabled, the assert will fail and an AssertionError will be thrown. Alternative is: default: throw new AssertionError(suit); This alternative offers protection even if assertions are disabled
  • 51. Control-Flow Invariants Place an assertion at any location you assume will not be reached. The assertions statement to use is: assert false; For example, suppose you have a method that looks like this: void foo() { for (...) { if (...) return; } // Execution should never reach this point!!! }
  • 52. Replace the final comment so that the code now reads: void foo() { for (...) { if (...) return; } assert false; // Execution should never reach this point! }
  • 53. Preconditions & Postconditions By convention, preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. For example: public void setRefreshRate(int rate) { // Enforce specified precondition in public method if (rate <= 0 || rate > MAX_REFRESH_RATE) throw new IllegalArgumentException(&quot;Illegal rate: &quot; + rate); setRefreshInterval(1000/rate); } This convention is unaffected by the addition of the assert construct.
  • 54.
  • 55. However assertion can be used to test a non public method's precondition. If you write a private method, you almost certainly wrote (or control) any code that calls it. When you assume that the logic in code calling your private method is correct, you can test that assumption with an assertion as follows: private void doMore(int x) { assert (x > 0); // do things with x } Remember You're certainly free to compile assertion code with an inappropriate validation of public arguments,
  • 56. Don't Use assertions to validate Command-Line arguments If your program requires command-line arguments, you'll probably use the exception mechanism to enforce them.
  • 57.
  • 58. If using a Java 1.4 compiler , and also using assert as a keyword (in other words, you're actually trying to assert something in your code), then you must explicitly enable assertion-awareness at compile time, as follows: javac -source 1.4 com/geeksanonymous/TestClass.java The Java 5 compiler will use the assert keyword by default, the compiler will generate an error message if it finds the word assert used as an identifier. However, you can tell the compiler that you're giving it an old piece of code to compile, javac -source 1.3 OldCode.java
  • 59. What will happen in the following case Suppose the program is using the assert as an identifier and you compile using javac -source 1.4 NotQuiteSoOldCode.java Will the code compile?
  • 60. In this case, the compiler will issue errors when it discovers the word assert used as an identifier. Using Java 5 Compiler
  • 61. Enable Assertions Programmers of certain critical systems might wish to ensure that assertions are not disabled in the field. The following static initialization idiom prevents a class from being initialized if its assertions have been disabled: static { boolean assertsEnabled = false; assert assertsEnabled = true; // Intentional side effect!!! if (!assertsEnabled) throw new RuntimeException(&quot;Asserts must be enabled!!!&quot;); }
  • 62.
  • 63. Selective Enabling and Disabling no arguments    Enables or disables assertions in all classes except system classes. packageName ...    Enables or disables assertions in the named package and any subpackages. className    Enables or disables assertions in the named class
  • 64. For example, java -ea:com.wombat.fruitbat BatTutor The following command runs a program, BatTutor, with assertions enabled in only package com.wombat.fruitbat and its subpackages: -enablesystemassertions, or -esa. To enable assertions in all system classes. java -ea -da:com.geeksanonymous.Foo this tells the JVM to enable assertions in general, but disable them in the class com.geeksanonymous.Foo. java -ea -da:com.geeksanonymous... tells the JVM to enable assertions in general, but disable them in the package com.geeksanonymous, and all of its subpackages!