SlideShare a Scribd company logo
Module 8     Exceptions & Assertions
Objectives •  Define exceptions  •  Use try, catch, and finally statements  •  Describe exception categories  •  Identify common exceptions  •  Develop programs to handle your own exceptions •  Use Assertions •  Distinguish appropriate and inappropriate uses of assertion. •  Enable assertions at runtime.
Exception An event during program execution that prevents the  program from continuing normally . like user might enter an invalid filename . a file might contain corrupted data .   a network link could fail  a bug in the program might cause it to try to make  an illegal memory acces s Circumstances of this type are called exception  conditions in Java.
Call Stack Suppose your program starts in method main() , main() method calls method a() which calls method b(),  which in turn calls method c().  The call stack consists of the following: c b a main the last method called is at the top of the stack, while the first calling  method is at the bottom.
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
The runtime system searches the call stack for a method  that contains a block of code that can handle the  exception. This block of code is called an  exception handler . The search begins with the method in which the error  occurred and proceeds through the call stack in the  reverse order in which the methods were called.   When an appropriate handler is found, the runtime  system passes the exception to the handler.
Example  DodgeException.java
 
 
Checked Exception   These are the exceptional condition that a well  written application should anticipate and recover from. For example suppose an application prompts a user  for an input filename, the user supplies the name of  a nonexistent file, and the constructor throws  java.io.FileNotFound Exception.  A well-written program will catch this exception  and notify the user of the mistake  Java compiler check programmer has stated what is to  be done when they arise and because of this checking  they are  called checked exception. Example TestCheckException.java
Runtime exception These are  exceptional conditions  that are  internal to  the  application , and that the application usually  cannot  anticipate  or  recover from.   These usually indicate programming bugs, such as divison by zero  and invalid array indexing. An object of type RuntimeException may be thrown from any  method without being specified as part of the method's public  interface
Error   These are exceptional conditions that are  external to  the application , and that the  application  usually  cannot   anticipate or  recover from. For example , suppose that an application successfully  opens a file for input, but is unable to read the file  because of a hardware or system malfunction.  The unsuccessful read will throw java.io.IOError. Stack overflow is also example of an Error. You may also throw an Error yourself, for example AssertionError Example  TestError.java
Why the compiler doesnot require you to catch  Runtime exceptions?   Runtime exceptions represent problems that are the  result of a  programming problem  such problems  include arithmetic exceptions, such as dividing by zero;  pointer exceptions,such as trying to access an object  through a null reference; and indexing exceptions, such  as attempting to access an array element through an  index that is too large or too small.    Runtime exceptions  can occur anywhere  in a  program , having to add runtime exceptions in every  method declaration would reduce a program's clarity.  Thus, the compiler does not require that you catch or  specify runtime exceptions
Ways  to check checked exceptions Two ways  to check checked exceptions Put the  try  block around the code that might throw the  exception and provide a corresponding  catch  block that  will apply to exception in question. Doing so handles  the exception  Second way is method declaration includes  a  throws  part that inform caller the exception  might arise. By doing so the responsibility for handling  the exception is explicitly passed to caller of method.
Three statements   in handling exceptions   The  try statement  identifies a block of statements  within which an exception might be thrown. The  catch statement  must be associated with a  try   statement and identifies a block of statements that  can handle a particular type of exception. The  statements are executed if an exception of a particular  type occurs within the  try  block.  The  finally statement  must be associated with a try  statement and identifies a block of statements that  are executed regardless of whether or not an error  occurs within the try block.
T he general form of these statements: try {  statement(s) }  catch ( exceptiontype   name ){ statement(s) }  finally {  statement(s) }   If the exception is thrown in try block and is caught by  matching catch block; the exception is considered to  have been handled.
Will this codes compile 1.   try{ //do Stuff } System.out.println(“Hello World”); catch(Exception e){ } 2. try { // do risky IO things } catch (IOException e) { // handle general IOExceptions } catch (FileNotFoundException ex) { // handle just FileNotFoundException }
3. public void doStuff() { try { // risky IO things } catch(IOException ex) { throw ex; } }
Exception Example class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } When the Java run-time system detects the attempt to  divide by zero, it constructs a new exception object and  then  throws  this exception. Exception is caught by the default handler provided  by the   Java run-time system.
The resulting stack trace from the default exception  handler shows how the entire call stack is displayed: Exception in thread "main" java.lang.ArithmeticException:  / by zero at Exc0.main(Exc0.java:4)
Exception Example Revisited class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { System.out.println("Division by zero."); } System.out.println("After catch statement."); } }
This program generates the following output: Division by zero. After catch statement. Once an exception is thrown, program control  transfers out of the  try  block into the  catch  block. Once the  catch  statement has executed, program control  continues with the next line in the program following the entire  try / catch  mechanism.
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
Catching Multiple Exception   (Example  MultiCatch.java ) Catch block catch the exceptions of the class specified  including any exceptions that are subclass of the one specified. In order to handle more specific exceptions in one  particular catch block ,specify one exception class in one  catch block and parent class of that exception in another  catch block this way we can handle more specific  exception separately from general exception .
Under such conditions follow these two rules 1.A more specific catch block  must precede a  more general one, otherwise compiler error. Example  SuperSubCatch.java 2.Only one catch block the most applicable one will  be executed.
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.
What would happen when you compile and run the following  program? class ThrowsDemo { static void throwOne() { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { throwOne(); } }
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.
// This is now correct. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println("Inside throwOne."); throw new IllegalAccessException("demo"); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println("Caught " + e); } } }
The throw statement Throwing an exception in its most basic form is simple . Two steps involved in throwing an exception are  1. Create an instance of an object that is subclass of  java.lang.Throwable. 2. Use throw keyword to actually throw the exception.   These two are combined into a single statement  like this   throw new IOException(“File not found”); Example  ThrowDemo.java
Finally  (FinallyDemo.java) finally   creates a block of code that will be  executed after a  try / catch  block has completed  and before the code following the  try/catch  block. The  finally  block will execute whether or not an  exception is thrown.  If an exception is thrown, the  finally  block will  execute even if no  catch  statement matches  the exception. Finally block generally contain the clean up code.
Exception and Overriding Consider if you extend a class and override a method  the Java compiler insists that all exception classes thrown by  the new method be the same as subclass of  the exception  classes thrown by original method. Example public class BaseClass{ public void method() throws IOException{ } } public class LegalOne extends BaseClass{ public void method() throws IOException{ } }
public class LegalTwo extends BaseClass{ public void method(){ } } public class LegalThree extends BaseClass{ public void method() throws EOFException, MalformedURLException{ } } public class IllegalOne extends BaseClass{ public void method() throws IOException, IllegalAccessException{ } }
  Method Overriding and Exceptions •  Must throw exceptions that are the same class as the exceptions being thrown by the overridden method •  May throw exceptions that are subclasses of the exceptions being thrown by the overridden method •  If a superclass method throws multiple exceptions,  the overriding method must throw a proper subset of  exceptions thrown by the overridden method    Example  TestExceptionA.java
Creating Your Own Exceptions This program creates a custom exception type. class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return "MyException[" + detail + "]"; } }  
class ExceptionDemo { static void compute(int a) throws MyException { System.out.println("Called compute(" + a + ")"); if(a > 10) throw new MyException(a); System.out.println("Normal exit"); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println("Caught " + e); } } }
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);} }
Using Assertions write the earlier code as private void methodA(int num) { assert (num>=0);  // throws an AssertionError if this test isn't true useNum(num + x); } So each assertion contains a boolean expression that will be true  when the assertion executes. If it is not true, the system will throw  an error.  Assertions work quite simply. You always assert that something  is true. If it is, no problem. Code keeps running. But if your assertion  turns out to be wrong (false), then AssertionError is thrown
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.
Example  private void doStuff() { assert (y > x): &quot;y is &quot; + y + &quot; x is &quot; + x; // more code assuming y is greater than x }
Appropriate and Inappropriate uses of Assertion Situations where it is good to use assertions.  Internal Invariants  Control-Flow Invariants  Preconditions & Postconditions
Internal Invariants Before assertions were available, many programmers used  comments to indicate their assumptions concerning a program's  behavior.  if (i % 3 == 0) { ...  } else if (i % 3 == 1) { ...  } else {  // We know (i % 3 == 2)   ...  }
Rewriting the previous if-statement using assertions if (i % 3 == 0) {  ...  } else if (i % 3 == 1) {  ...  } else {  assert i % 3 == 2 : i;   ...  }
Suppose the following switch statement appears in a program that  handles playing cards:  switch(suit) {  case Suit.CLUBS:  ...  break;  case Suit.DIAMONDS:  ...  break;  case Suit.HEARTS:  ...  break;  case Suit.SPADES:  ...  }
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.
Don't Use assertions to validate arguments to a Public Method The following is an inappropriate use of assertions: public void doStuff(int x) { assert (x > 0); // inappropriate ! // do things with x } A public method might be called from code that you don't control because public methods are part of your interface to the outside  world, you're supposed to guarantee that any constraints on the  arguments will be enforced by the method itself. But since assertions aren't guaranteed to actually run the  enforcement won't happen if assertions aren't enabled.
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.
Identifier vs Keyword Prior to version 1.4,  int assert = getInitialValue(); if (assert == getActualResult()) { // do something } assert is used as an identifier.  But you cannot use a keyword/reserved  word as an identifier,  and beginning with version 1.4, assert is a keyword. You can use assert as a keyword or as an identifier, but not both.
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;);  }
Enabling and Disabling Assertions   By default, assertions are disabled at runtime.  Two command-line switches allow you to selectively enable or  disable assertions. To enable assertions use the -enableassertions, or -ea  java -ea com.geeksanonymous.TestClass java -enableassertions com.geeksanonymous.TestClass To disable assertions use the -disableassertions or -da,  java -da com.geeksanonymous.TestClass java -disableassertions com.geeksanonymous.TestClass
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!

More Related Content

PPT
Exception handling
PPTX
Java exception handling
PPT
exception handling
PPT
12 exception handling
PPT
Chap12
PPT
9781439035665 ppt ch11
PPTX
Interface andexceptions
PPT
Java: Exception
Exception handling
Java exception handling
exception handling
12 exception handling
Chap12
9781439035665 ppt ch11
Interface andexceptions
Java: Exception

What's hot (20)

PPT
Exception Handling Java
PPTX
Exception Handling in Java
PPTX
Exception handling in Java
PDF
Built in exceptions
PPT
Exception handling in java
PPTX
Exception Handling in Java
PPTX
Java exception handling
PPTX
Exception handling in java
PPTX
Java Exception Handling and Applets
PPTX
Exceptions overview
ODP
Exception Handling In Java
PPTX
7.error management and exception handling
PPTX
Exceptionhandling
PPTX
Chap2 exception handling
ODP
Exception handling in java
PPTX
Exception handling in java
PPT
Exception handling
PPT
Exception handling
PPT
exception handling in java
PPT
Exception handling
Exception Handling Java
Exception Handling in Java
Exception handling in Java
Built in exceptions
Exception handling in java
Exception Handling in Java
Java exception handling
Exception handling in java
Java Exception Handling and Applets
Exceptions overview
Exception Handling In Java
7.error management and exception handling
Exceptionhandling
Chap2 exception handling
Exception handling in java
Exception handling in java
Exception handling
Exception handling
exception handling in java
Exception handling
Ad

Similar to Md07 exceptions&assertion (20)

PPTX
Java -Exception handlingunit-iv
PDF
Java exceptions
PPTX
130410107010 exception handling
PPTX
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
PPTX
Exception Handling In Java Presentation. 2024
PPTX
Java-Exception Handling Presentation. 2024
PPTX
Exception Handling,finally,catch,throw,throws,try.pptx
PPTX
unit 4 msbte syallbus for sem 4 2024-2025
PPTX
UNIT 2.pptx
PPTX
Z blue exception
PPT
Exceptions &amp; Its Handling
PPTX
Exception handling in java
PPTX
java exception.pptx
DOCX
Java Exception handling
PPTX
Exception‐Handling in object oriented programming
PDF
Exception handling
PDF
Exception handling
PPT
Exceptionhandling
PPTX
Java SE 11 Exception Handling
PPT
Exception Handling in java masters of computer application
Java -Exception handlingunit-iv
Java exceptions
130410107010 exception handling
Module 4.pptxModule 4.pptxModuModule 4.pptxModule 4.pptxle 4.pptx
Exception Handling In Java Presentation. 2024
Java-Exception Handling Presentation. 2024
Exception Handling,finally,catch,throw,throws,try.pptx
unit 4 msbte syallbus for sem 4 2024-2025
UNIT 2.pptx
Z blue exception
Exceptions &amp; Its Handling
Exception handling in java
java exception.pptx
Java Exception handling
Exception‐Handling in object oriented programming
Exception handling
Exception handling
Exceptionhandling
Java SE 11 Exception Handling
Exception Handling in java masters of computer application
Ad

More from Rakesh Madugula (13)

PPT
New features and enhancement
PPT
Md13 networking
PPT
Md121 streams
PPT
Md11 gui event handling
PPT
Md10 building java gu is
PPT
Md09 multithreading
PPT
Md08 collection api
PPT
Md06 advance class features
PPT
Md05 arrays
PPT
Md04 flow control
PPT
Md03 - part3
PPT
Md02 - Getting Started part-2
PPT
A begineers guide of JAVA - Getting Started
New features and enhancement
Md13 networking
Md121 streams
Md11 gui event handling
Md10 building java gu is
Md09 multithreading
Md08 collection api
Md06 advance class features
Md05 arrays
Md04 flow control
Md03 - part3
Md02 - Getting Started part-2
A begineers guide of JAVA - Getting Started

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
01-Introduction-to-Information-Management.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Sports Quiz easy sports quiz sports quiz
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Types and Its function , kingdom of life
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
master seminar digital applications in india
PDF
Complications of Minimal Access Surgery at WLH
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Insiders guide to clinical Medicine.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Microbial diseases, their pathogenesis and prophylaxis
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
01-Introduction-to-Information-Management.pdf
Supply Chain Operations Speaking Notes -ICLT Program
human mycosis Human fungal infections are called human mycosis..pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Sports Quiz easy sports quiz sports quiz
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Types and Its function , kingdom of life
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
master seminar digital applications in india
Complications of Minimal Access Surgery at WLH
Anesthesia in Laparoscopic Surgery in India
Insiders guide to clinical Medicine.pdf
TR - Agricultural Crops Production NC III.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf

Md07 exceptions&assertion

  • 1. Module 8 Exceptions & Assertions
  • 2. Objectives • Define exceptions • Use try, catch, and finally statements • Describe exception categories • Identify common exceptions • Develop programs to handle your own exceptions • Use Assertions • Distinguish appropriate and inappropriate uses of assertion. • Enable assertions at runtime.
  • 3. Exception An event during program execution that prevents the program from continuing normally . like user might enter an invalid filename . a file might contain corrupted data . a network link could fail a bug in the program might cause it to try to make an illegal memory acces s Circumstances of this type are called exception conditions in Java.
  • 4. Call Stack Suppose your program starts in method main() , main() method calls method a() which calls method b(), which in turn calls method c(). The call stack consists of the following: c b a main the last method called is at the top of the stack, while the first calling method is at the bottom.
  • 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. The runtime system searches the call stack for a method that contains a block of code that can handle the exception. This block of code is called an exception handler . The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called. When an appropriate handler is found, the runtime system passes the exception to the handler.
  • 12.  
  • 13.  
  • 14. Checked Exception These are the exceptional condition that a well written application should anticipate and recover from. For example suppose an application prompts a user for an input filename, the user supplies the name of a nonexistent file, and the constructor throws java.io.FileNotFound Exception. A well-written program will catch this exception and notify the user of the mistake Java compiler check programmer has stated what is to be done when they arise and because of this checking they are called checked exception. Example TestCheckException.java
  • 15. Runtime exception These are exceptional conditions that are internal to the application , and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as divison by zero and invalid array indexing. An object of type RuntimeException may be thrown from any method without being specified as part of the method's public interface
  • 16. Error These are exceptional conditions that are external to the application , and that the application usually cannot anticipate or recover from. For example , suppose that an application successfully opens a file for input, but is unable to read the file because of a hardware or system malfunction. The unsuccessful read will throw java.io.IOError. Stack overflow is also example of an Error. You may also throw an Error yourself, for example AssertionError Example TestError.java
  • 17. Why the compiler doesnot require you to catch Runtime exceptions? Runtime exceptions represent problems that are the result of a programming problem such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions,such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small. Runtime exceptions can occur anywhere in a program , having to add runtime exceptions in every method declaration would reduce a program's clarity. Thus, the compiler does not require that you catch or specify runtime exceptions
  • 18. Ways to check checked exceptions Two ways to check checked exceptions Put the try block around the code that might throw the exception and provide a corresponding catch block that will apply to exception in question. Doing so handles the exception Second way is method declaration includes a throws part that inform caller the exception might arise. By doing so the responsibility for handling the exception is explicitly passed to caller of method.
  • 19. Three statements in handling exceptions   The try statement identifies a block of statements within which an exception might be thrown. The catch statement must be associated with a try statement and identifies a block of statements that can handle a particular type of exception. The statements are executed if an exception of a particular type occurs within the try block. The finally statement must be associated with a try statement and identifies a block of statements that are executed regardless of whether or not an error occurs within the try block.
  • 20. T he general form of these statements: try { statement(s) } catch ( exceptiontype name ){ statement(s) } finally { statement(s) } If the exception is thrown in try block and is caught by matching catch block; the exception is considered to have been handled.
  • 21. Will this codes compile 1. try{ //do Stuff } System.out.println(“Hello World”); catch(Exception e){ } 2. try { // do risky IO things } catch (IOException e) { // handle general IOExceptions } catch (FileNotFoundException ex) { // handle just FileNotFoundException }
  • 22. 3. public void doStuff() { try { // risky IO things } catch(IOException ex) { throw ex; } }
  • 23. Exception Example class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. Exception is caught by the default handler provided by the Java run-time system.
  • 24. The resulting stack trace from the default exception handler shows how the entire call stack is displayed: Exception in thread &quot;main&quot; java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4)
  • 25. Exception Example Revisited class Exc2 { public static void main(String args[]) { int d, a; try { d = 0; a = 42 / d; System.out.println(&quot;This will not be printed.&quot;); } catch (ArithmeticException e) { System.out.println(&quot;Division by zero.&quot;); } System.out.println(&quot;After catch statement.&quot;); } }
  • 26. This program generates the following output: Division by zero. After catch statement. Once an exception is thrown, program control transfers out of the try block into the catch block. Once the catch statement has executed, program control continues with the next line in the program following the entire try / catch mechanism.
  • 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. Catching Multiple Exception (Example MultiCatch.java ) Catch block catch the exceptions of the class specified including any exceptions that are subclass of the one specified. In order to handle more specific exceptions in one particular catch block ,specify one exception class in one catch block and parent class of that exception in another catch block this way we can handle more specific exception separately from general exception .
  • 29. Under such conditions follow these two rules 1.A more specific catch block must precede a more general one, otherwise compiler error. Example SuperSubCatch.java 2.Only one catch block the most applicable one will be executed.
  • 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. What would happen when you compile and run the following program? class ThrowsDemo { static void throwOne() { System.out.println(&quot;Inside throwOne.&quot;); throw new IllegalAccessException(&quot;demo&quot;); } public static void main(String args[]) { throwOne(); } }
  • 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. // This is now correct. class ThrowsDemo { static void throwOne() throws IllegalAccessException { System.out.println(&quot;Inside throwOne.&quot;); throw new IllegalAccessException(&quot;demo&quot;); } public static void main(String args[]) { try { throwOne(); } catch (IllegalAccessException e) { System.out.println(&quot;Caught &quot; + e); } } }
  • 34. The throw statement Throwing an exception in its most basic form is simple . Two steps involved in throwing an exception are 1. Create an instance of an object that is subclass of java.lang.Throwable. 2. Use throw keyword to actually throw the exception.   These two are combined into a single statement like this throw new IOException(“File not found”); Example ThrowDemo.java
  • 35. Finally (FinallyDemo.java) finally creates a block of code that will be executed after a try / catch block has completed and before the code following the try/catch block. The finally block will execute whether or not an exception is thrown. If an exception is thrown, the finally block will execute even if no catch statement matches the exception. Finally block generally contain the clean up code.
  • 36. Exception and Overriding Consider if you extend a class and override a method the Java compiler insists that all exception classes thrown by the new method be the same as subclass of the exception classes thrown by original method. Example public class BaseClass{ public void method() throws IOException{ } } public class LegalOne extends BaseClass{ public void method() throws IOException{ } }
  • 37. public class LegalTwo extends BaseClass{ public void method(){ } } public class LegalThree extends BaseClass{ public void method() throws EOFException, MalformedURLException{ } } public class IllegalOne extends BaseClass{ public void method() throws IOException, IllegalAccessException{ } }
  • 38. Method Overriding and Exceptions • Must throw exceptions that are the same class as the exceptions being thrown by the overridden method • May throw exceptions that are subclasses of the exceptions being thrown by the overridden method • If a superclass method throws multiple exceptions, the overriding method must throw a proper subset of exceptions thrown by the overridden method Example TestExceptionA.java
  • 39. Creating Your Own Exceptions This program creates a custom exception type. class MyException extends Exception { private int detail; MyException(int a) { detail = a; } public String toString() { return &quot;MyException[&quot; + detail + &quot;]&quot;; } }  
  • 40. class ExceptionDemo { static void compute(int a) throws MyException { System.out.println(&quot;Called compute(&quot; + a + &quot;)&quot;); if(a > 10) throw new MyException(a); System.out.println(&quot;Normal exit&quot;); } public static void main(String args[]) { try { compute(1); compute(20); } catch (MyException e) { System.out.println(&quot;Caught &quot; + e); } } }
  • 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. Using Assertions write the earlier code as private void methodA(int num) { assert (num>=0); // throws an AssertionError if this test isn't true useNum(num + x); } So each assertion contains a boolean expression that will be true when the assertion executes. If it is not true, the system will throw an error. Assertions work quite simply. You always assert that something is true. If it is, no problem. Code keeps running. But if your assertion turns out to be wrong (false), then AssertionError is thrown
  • 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. Example private void doStuff() { assert (y > x): &quot;y is &quot; + y + &quot; x is &quot; + x; // more code assuming y is greater than x }
  • 46. Appropriate and Inappropriate uses of Assertion Situations where it is good to use assertions. Internal Invariants Control-Flow Invariants Preconditions & Postconditions
  • 47. Internal Invariants Before assertions were available, many programmers used comments to indicate their assumptions concerning a program's behavior. if (i % 3 == 0) { ... } else if (i % 3 == 1) { ... } else { // We know (i % 3 == 2) ... }
  • 48. Rewriting the previous if-statement using assertions if (i % 3 == 0) { ... } else if (i % 3 == 1) { ... } else { assert i % 3 == 2 : i; ... }
  • 49. Suppose the following switch statement appears in a program that handles playing cards: switch(suit) { case Suit.CLUBS: ... break; case Suit.DIAMONDS: ... break; case Suit.HEARTS: ... break; case Suit.SPADES: ... }
  • 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. Don't Use assertions to validate arguments to a Public Method The following is an inappropriate use of assertions: public void doStuff(int x) { assert (x > 0); // inappropriate ! // do things with x } A public method might be called from code that you don't control because public methods are part of your interface to the outside world, you're supposed to guarantee that any constraints on the arguments will be enforced by the method itself. But since assertions aren't guaranteed to actually run the enforcement won't happen if assertions aren't enabled.
  • 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. Identifier vs Keyword Prior to version 1.4, int assert = getInitialValue(); if (assert == getActualResult()) { // do something } assert is used as an identifier. But you cannot use a keyword/reserved word as an identifier, and beginning with version 1.4, assert is a keyword. You can use assert as a keyword or as an identifier, but not both.
  • 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. Enabling and Disabling Assertions By default, assertions are disabled at runtime. Two command-line switches allow you to selectively enable or disable assertions. To enable assertions use the -enableassertions, or -ea java -ea com.geeksanonymous.TestClass java -enableassertions com.geeksanonymous.TestClass To disable assertions use the -disableassertions or -da, java -da com.geeksanonymous.TestClass java -disableassertions com.geeksanonymous.TestClass
  • 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!