SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
[Effective Java by Joshua Bloch]
   try {
   int i = 0;
   while(true)
   range[i++].climb();
   } catch(ArrayIndexOutOfBoundsException e) {
   }
   Because exceptions are designed for exceptional
    circumstances, they should only be used for exceptional
    behaviors and should not drive the control flow of any program.
   In the presence of an unrelated bug, the loop can fail silently
    and mask the bug.
   the computation in the body of the loop may invoke a method
    that performs an out-of-bounds access to some unrelated
    array, and kill the execution silently.
   exceptions ;as the name suggests ,should be used only for
    exceptional conditions; they should never be used for ordinary
    control flow.
   An API must not force its clients to use exceptions for ordinary
    control flow.

   A class with a “state-dependent” method that can be invoked only
    under certain unpredictable conditions should generally have a
    separate “state-testing” method indicating whether it is appropriate
    to invoke the state-dependent method.
   try {
   Iterator<Foo> i = collection.iterator();
   while(true) {
   Foo foo = i.next();
   ...
   }
   } catch (NoSuchElementException e) {
   }
                       ---vs----

   for (Iterator<Foo> i = collection.iterator(); i.hasNext(); ) {
   Foo foo = i.next();
   ...
   }

   when exception happens if client code cannot do anything ,make it
    an unchecked exception
   If client code can take some useful recovery action based on
    information in exception, make it a checked exception
   By throwing a checked exception, you force the caller to handle the
    exception in a catch clause or to propagate it outward.
   Each checked exception that a method is declared to throw is
    therefore a potent indication to the API user that the associated
    condition is a possible outcome of invoking the method.
   public void dataAccessCode()
   {
    try{
    ..some code that throws SQLException }
   catch(SQLException ex){
    ex.printStacktrace();
    }
   }
   public void dataAccessCode()
   {
    try{
    ..some code that throws SQLException
    }
   catch(SQLException ex){
   throw new RuntimeException(ex);
   }
    }
   import javax.swing.JOptionPane;
    public class DialogBoxInput
    {
      public static void main( String [] args )
      {
        // declare and initialize variables that will be
        // assigned values in the try block
        int n = 0;
        boolean goodInput = false; // flag variable
            // priming read
            String s = JOptionPane.showInputDialog( null, "Enter an integer" );
            do
            {
              try
              {
                // attempt to convert the String to an int
                n = Integer.parseInt( s );
                goodInput = true;
              }
              catch ( NumberFormatException nfe )
              {
                s = JOptionPane.showInputDialog( null,
                             s + " is not an integer. "
                             + "Enter an integer" );
              }
            } while ( !goodInput );
            JOptionPane.showMessageDialog( null, "The integer is " + n );
        }
    }
   Checked exceptions should be used if it allows the API user to
    recover from the exceptions.
   One technique for turning a checked exception into an unchecked
    exception is to break the method that throws the exception into two
    methods, the first of which returns a boolean that indicates whether
    the exception would be thrown. This API refactoring transforms the
    calling sequence from this:
   Invocation with checked exception.

   try {
   obj.action(args);
   } catch(TheCheckedException e) {
   // Handle exceptional condition
   ...
   }
                                 ---vs---

   Invocation with state-testing method and unchecked exception.

   if (obj.actionPermitted(args)) {
   obj.action(args);
   } else {
   // Handle exceptional condition
   ...
   }
   if an object is to be accessed concurrently without external
    synchronization or it is subject to externally induced state
    transitions, this refactoring is inappropriate, as the object’s state
    may change between the invocations of actionPermitted and action.
   Makes our API easier to learn and use because it matches
    established conventions with which programmers are already
    familiar.
    Programs using our API are easier to read because they aren’t
    cluttered with unfamiliar exceptions.
   Fewer exception classes mean a smaller memory footprint and less
    time spent loading classes
   Higher layers should catch lower-level exceptions and, in
    their place, throw exceptions that can be explained in terms
    of the higher-level abstraction
   public E get(int index) {
   ListIterator<E> i = listIterator(index);
   try {
   return i.next();
   } catch(NoSuchElementException e) {
   throw new IndexOutOfBoundsException("Index: " + index);
   }
   }
   try {
   // Use lower-level abstraction to do our bidding
   } catch (LowerLevelException cause) {
   throw new HigherLevelException(cause);
   }

   The higher-level exception’s constructor passes the cause to
    a chaining-aware superclass constructor, so it is ultimately
    passed to one of Throwable’s chaining aware
    constructors, such as Throwable(Throwable).
   Where possible, the best way to deal with exceptions from lower
    layers is to avoid them, by ensuring that lower-level methods
    succeed. Sometimes you can do this by checking the validity of the
    higher-level method’s parameters before passing them on to lower
    layers.
   Always declare checked exceptions individually, and document
    precisely the conditions under which each one is thrown using the
    Javadoc @throws tag.
   Use the Javadoc @throws tag to document each unchecked
    exception that a method can throw, but do not use the throws
    keyword to include unchecked exceptions in the method declaration.
   If an exception is thrown by many methods in a class for the same
    reason,it is acceptable to document the exception in the class’s
    documentation comment
   To capture the failure, the detail message of an exception should
    contain the values of all parameters and fields that “contributed to
    the exception.”
   One way to ensure that exceptions contain adequate failure-capture
    information in their detail messages is to require this information in
    their constructors instead of a string detail message.
   /**
   * Construct an IndexOutOfBoundsException.
   *
   * @param lowerBound the lowest legal index value.
   * @param upperBound the highest legal index value plus one.
   * @param index the actual index value.
   */
   public IndexOutOfBoundsException(int lowerBound, int upperBound,
   int index) {
   super("Lower bound: " + lowerBound +
   ", Upper bound: " + upperBound +
   ", Index: " + index);
   // Save failure information for programmatic access
   this.lowerBound = lowerBound;
   this.upperBound = upperBound;
   this.index = index;
   }
   It is more important to provide such accessor methods on checked
    exceptions than on unchecked exceptions, because the failure
    capture information could be useful in recovering from the failure
   a failed method invocation should leave the object in the state that it
    was in prior to the invocation.
   Some of the methods check parameters for validity before
    performing the operation. This causes any exception to get thrown
    before object modification commences.
   public Object pop() {
   if (size == 0)
   throw new EmptyStackException();
   Object result = elements[--size];
   elements[size] = null; // Eliminate obsolete
    reference
   return result;
   }
   Another approach to achieving failure atomicity is to write recovery
    code that intercepts a failure that occurs in the midst of an
    operation and causes the object to roll back its state to the point
    before the operation began.
   To achieve failure atomicity is to perform the operation on a
    temporary copy of the object and to replace the contents of the
    object with the temporary copy once the operation is complete.
   try {
   ...
   } catch (SomeException e) {
   }

The purpose of exceptions is defeated here.
   Pluggable exception handlers is a technique that allows the users of
    a component to customize the exception handling of that
    component. Instead of handling, enriching, wrapping and/or logging
    the exception, the exception handling is delegated to an exception
    handler.
   public interface ExceptionHandler
    {
    public void handle(Exception e, String errorMessage);
   }
   public class WrappingHandler implements ExceptionHandler
    {
    public void handle(Exception e, String message)
   {
   throw new RuntimeException(message, e);
   }
   }
   public class CollectingHandler implements ExceptionHandler
   {
   List exceptions = new ArrayList();
   public List getExceptions()
   {
    return this.exceptions;
   }
   public void handle(Exception e, String message)
   {
   this.exceptions.add(e); //message is ignored here, but could
    //have been collected too.
   }
    }
   public class Component{
   protected ExceptionHandler exceptionHandler = null;
   public void setExceptionHandler(ExceptionHandler handler){
    this.exceptionHandler = handler;
   }
   public void processFile(String fileName){
   FileInputStream input = null;
    try{
    input = new FileInputStream(fileName); processStream(input);
    }
   catch (IOException e){
    this.exceptionHandler.handle(e, "error processing file: " + fileName);
    }
    }
   protected void processStream(InputStream input) throws IOException{
    //do something with the stream.
    }
   }
   Pluggable exception handlers are most effective in situations
    where the exceptions occurring can be handled sensibly in
    different ways. For instance, when validating an XML
    document, or an HTML form, you may not always want to
    stop the validation at the first validation error. In some
    situations you might want to continue validation to catch all
    validation exceptions thrown, and show them all to the user
    at the same time. This saves the user from having to correct
    an error, validate, correct error, validate over and over again.
    All errors can be caught and corrected in one iteration.
InputStream input = null;
 try{
 input = new FileInputStream("myFile.txt");
 //do something with the stream
} catch(IOException e){
throw new AException(e);
} finally {
 try{
 input.close();
 } catch(IOException e){
 throw new BException(e);
 }
 }
   The last exception thrown in a try-catch-finally block is the
    exception that will be propagated up the call stack. All earlier
    exceptions will disappear.
   InputStream input = null;
    try{
   input = new FileInputStream("myFile.txt"); //do something with the
    stream
   } catch(IOException e){
   //first catch block
    throw new WrapperException(e);
   } finally {
    try{
   if(input != null) input.close();
    } catch(IOException e){
   //second catch block
   throw new WrapperException(e);
    }
    }
Exception

Contenu connexe

Tendances

JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework OverviewMario Peshev
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cppgourav kottawar
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8Sergiu Mircea Indrie
 
Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerPVS-Studio
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Editionlosalamos
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]ppd1961
 
Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)Will Shen
 
10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java ApplicationsEberhard Wolff
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#Raghu nath
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 

Tendances (20)

Java unit3
Java unit3Java unit3
Java unit3
 
JMockit Framework Overview
JMockit Framework OverviewJMockit Framework Overview
JMockit Framework Overview
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Exception handling
Exception handlingException handling
Exception handling
 
exception handling in cpp
exception handling in cppexception handling in cpp
exception handling in cpp
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
FunctionalInterfaces
FunctionalInterfacesFunctionalInterfaces
FunctionalInterfaces
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Checking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzerChecking 7-Zip with PVS-Studio analyzer
Checking 7-Zip with PVS-Studio analyzer
 
Exception handling
Exception handlingException handling
Exception handling
 
Effective Java Second Edition
Effective Java Second EditionEffective Java Second Edition
Effective Java Second Edition
 
Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]Handling Exceptions In C &amp; C++[Part A]
Handling Exceptions In C &amp; C++[Part A]
 
Use me strict
Use me strictUse me strict
Use me strict
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 
Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)Junit Recipes - Elementary tests (2/2)
Junit Recipes - Elementary tests (2/2)
 
10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications10 Typical Problems in Enterprise Java Applications
10 Typical Problems in Enterprise Java Applications
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 

Similaire à Exception

Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its HandlingBharat17485
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentrohitgudasi18
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertionRakesh Madugula
 
Oop10 6
Oop10 6Oop10 6
Oop10 6schwaa
 
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
 
Java căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8Vince Vo
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012Sandeep Joshi
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfarjuntelecom26
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVARajan Shah
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practicesAngelin R
 

Similaire à Exception (20)

exception handling
exception handlingexception handling
exception handling
 
Exceptions &amp; Its Handling
Exceptions &amp; Its HandlingExceptions &amp; Its Handling
Exceptions &amp; Its Handling
 
Unit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application developmentUnit II Java & J2EE regarding Java application development
Unit II Java & J2EE regarding Java application development
 
3 j unit
3 j unit3 j unit
3 j unit
 
Md07 exceptions&assertion
Md07 exceptions&assertionMd07 exceptions&assertion
Md07 exceptions&assertion
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Oop10 6
Oop10 6Oop10 6
Oop10 6
 
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 căn bản - Chapter8
Java căn bản - Chapter8Java căn bản - Chapter8
Java căn bản - Chapter8
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Ensure code quality with vs2012
Ensure code quality with vs2012Ensure code quality with vs2012
Ensure code quality with vs2012
 
java write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdfjava write a program to evaluate the postfix expressionthe program.pdf
java write a program to evaluate the postfix expressionthe program.pdf
 
Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Exception handling
Exception handlingException handling
Exception handling
 
Rethrowing exception- JAVA
Rethrowing exception- JAVARethrowing exception- JAVA
Rethrowing exception- JAVA
 
Coding standards
Coding standardsCoding standards
Coding standards
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
Exception handling and logging best practices
Exception handling and logging best practicesException handling and logging best practices
Exception handling and logging best practices
 

Plus de Sandeep Chawla

Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objectsSandeep Chawla
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objectsSandeep Chawla
 
Sandeep Chawla Visual Resume
Sandeep Chawla Visual ResumeSandeep Chawla Visual Resume
Sandeep Chawla Visual ResumeSandeep Chawla
 

Plus de Sandeep Chawla (6)

Classes & Interfaces
Classes & InterfacesClasses & Interfaces
Classes & Interfaces
 
Methods common to all objects
Methods common to all objectsMethods common to all objects
Methods common to all objects
 
Concurrency
ConcurrencyConcurrency
Concurrency
 
Creating and destroying objects
Creating and destroying objectsCreating and destroying objects
Creating and destroying objects
 
Maven Introduction
Maven IntroductionMaven Introduction
Maven Introduction
 
Sandeep Chawla Visual Resume
Sandeep Chawla Visual ResumeSandeep Chawla Visual Resume
Sandeep Chawla Visual Resume
 

Dernier

Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceDr Vijay Vishwakarma
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research DiscourseAnita GoswamiGiri
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxAnupam32727
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptxmary850239
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQuiz Club NITW
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPCeline George
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDhatriParmar
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineCeline George
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxryandux83rd
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17Celine George
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...Nguyen Thanh Tu Collection
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptxmary850239
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfChristalin Nelson
 

Dernier (20)

Unit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional IntelligenceUnit :1 Basics of Professional Intelligence
Unit :1 Basics of Professional Intelligence
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
Scientific Writing :Research Discourse
Scientific  Writing :Research  DiscourseScientific  Writing :Research  Discourse
Scientific Writing :Research Discourse
 
CARNAVAL COM MAGIA E EUFORIA _
CARNAVAL COM MAGIA E EUFORIA            _CARNAVAL COM MAGIA E EUFORIA            _
CARNAVAL COM MAGIA E EUFORIA _
 
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptxCLASSIFICATION OF ANTI - CANCER DRUGS.pptx
CLASSIFICATION OF ANTI - CANCER DRUGS.pptx
 
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx4.9.24 School Desegregation in Boston.pptx
4.9.24 School Desegregation in Boston.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITWQ-Factor General Quiz-7th April 2024, Quiz Club NITW
Q-Factor General Quiz-7th April 2024, Quiz Club NITW
 
An Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERPAn Overview of the Calendar App in Odoo 17 ERP
An Overview of the Calendar App in Odoo 17 ERP
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptxDecoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
Decoding the Tweet _ Practical Criticism in the Age of Hashtag.pptx
 
Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
How to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command LineHow to Uninstall a Module in Odoo 17 Using Command Line
How to Uninstall a Module in Odoo 17 Using Command Line
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Employablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptxEmployablity presentation and Future Career Plan.pptx
Employablity presentation and Future Career Plan.pptx
 
How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17How to Manage Buy 3 Get 1 Free in Odoo 17
How to Manage Buy 3 Get 1 Free in Odoo 17
 
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
CHUYÊN ĐỀ ÔN THEO CÂU CHO HỌC SINH LỚP 12 ĐỂ ĐẠT ĐIỂM 5+ THI TỐT NGHIỆP THPT ...
 
4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx4.9.24 Social Capital and Social Exclusion.pptx
4.9.24 Social Capital and Social Exclusion.pptx
 
DiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdfDiskStorage_BasicFileStructuresandHashing.pdf
DiskStorage_BasicFileStructuresandHashing.pdf
 

Exception

  • 1. [Effective Java by Joshua Bloch]
  • 2.
  • 3. try {  int i = 0;  while(true)  range[i++].climb();  } catch(ArrayIndexOutOfBoundsException e) {  }
  • 4. Because exceptions are designed for exceptional circumstances, they should only be used for exceptional behaviors and should not drive the control flow of any program.  In the presence of an unrelated bug, the loop can fail silently and mask the bug.  the computation in the body of the loop may invoke a method that performs an out-of-bounds access to some unrelated array, and kill the execution silently.
  • 5. exceptions ;as the name suggests ,should be used only for exceptional conditions; they should never be used for ordinary control flow.
  • 6. An API must not force its clients to use exceptions for ordinary control flow.  A class with a “state-dependent” method that can be invoked only under certain unpredictable conditions should generally have a separate “state-testing” method indicating whether it is appropriate to invoke the state-dependent method.
  • 7. try {  Iterator<Foo> i = collection.iterator();  while(true) {  Foo foo = i.next();  ...  }  } catch (NoSuchElementException e) {  }  ---vs----  for (Iterator<Foo> i = collection.iterator(); i.hasNext(); ) {  Foo foo = i.next();  ...  } 
  • 8.
  • 9.
  • 10. when exception happens if client code cannot do anything ,make it an unchecked exception  If client code can take some useful recovery action based on information in exception, make it a checked exception
  • 11. By throwing a checked exception, you force the caller to handle the exception in a catch clause or to propagate it outward.  Each checked exception that a method is declared to throw is therefore a potent indication to the API user that the associated condition is a possible outcome of invoking the method.
  • 12. public void dataAccessCode()  {  try{  ..some code that throws SQLException }  catch(SQLException ex){  ex.printStacktrace();  }  }
  • 13. public void dataAccessCode()  {  try{  ..some code that throws SQLException  }  catch(SQLException ex){  throw new RuntimeException(ex);  }  }
  • 14. import javax.swing.JOptionPane; public class DialogBoxInput { public static void main( String [] args ) { // declare and initialize variables that will be // assigned values in the try block int n = 0; boolean goodInput = false; // flag variable // priming read String s = JOptionPane.showInputDialog( null, "Enter an integer" ); do { try { // attempt to convert the String to an int n = Integer.parseInt( s ); goodInput = true; } catch ( NumberFormatException nfe ) { s = JOptionPane.showInputDialog( null, s + " is not an integer. " + "Enter an integer" ); } } while ( !goodInput ); JOptionPane.showMessageDialog( null, "The integer is " + n ); } }
  • 15.
  • 16. Checked exceptions should be used if it allows the API user to recover from the exceptions.  One technique for turning a checked exception into an unchecked exception is to break the method that throws the exception into two methods, the first of which returns a boolean that indicates whether the exception would be thrown. This API refactoring transforms the calling sequence from this:
  • 17. Invocation with checked exception.  try {  obj.action(args);  } catch(TheCheckedException e) {  // Handle exceptional condition  ...  }  ---vs---  Invocation with state-testing method and unchecked exception.  if (obj.actionPermitted(args)) {  obj.action(args);  } else {  // Handle exceptional condition  ...  }
  • 18. if an object is to be accessed concurrently without external synchronization or it is subject to externally induced state transitions, this refactoring is inappropriate, as the object’s state may change between the invocations of actionPermitted and action.
  • 19.
  • 20. Makes our API easier to learn and use because it matches established conventions with which programmers are already familiar.  Programs using our API are easier to read because they aren’t cluttered with unfamiliar exceptions.  Fewer exception classes mean a smaller memory footprint and less time spent loading classes
  • 21.
  • 22. Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction
  • 23. public E get(int index) {  ListIterator<E> i = listIterator(index);  try {  return i.next();  } catch(NoSuchElementException e) {  throw new IndexOutOfBoundsException("Index: " + index);  }  }
  • 24. try {  // Use lower-level abstraction to do our bidding  } catch (LowerLevelException cause) {  throw new HigherLevelException(cause);  }  The higher-level exception’s constructor passes the cause to a chaining-aware superclass constructor, so it is ultimately passed to one of Throwable’s chaining aware constructors, such as Throwable(Throwable).
  • 25. Where possible, the best way to deal with exceptions from lower layers is to avoid them, by ensuring that lower-level methods succeed. Sometimes you can do this by checking the validity of the higher-level method’s parameters before passing them on to lower layers.
  • 26.
  • 27. Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag.  Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration.  If an exception is thrown by many methods in a class for the same reason,it is acceptable to document the exception in the class’s documentation comment
  • 28. To capture the failure, the detail message of an exception should contain the values of all parameters and fields that “contributed to the exception.”  One way to ensure that exceptions contain adequate failure-capture information in their detail messages is to require this information in their constructors instead of a string detail message.
  • 29. /**  * Construct an IndexOutOfBoundsException.  *  * @param lowerBound the lowest legal index value.  * @param upperBound the highest legal index value plus one.  * @param index the actual index value.  */  public IndexOutOfBoundsException(int lowerBound, int upperBound,  int index) {  super("Lower bound: " + lowerBound +  ", Upper bound: " + upperBound +  ", Index: " + index);  // Save failure information for programmatic access  this.lowerBound = lowerBound;  this.upperBound = upperBound;  this.index = index;  }
  • 30. It is more important to provide such accessor methods on checked exceptions than on unchecked exceptions, because the failure capture information could be useful in recovering from the failure
  • 31.
  • 32. a failed method invocation should leave the object in the state that it was in prior to the invocation.  Some of the methods check parameters for validity before performing the operation. This causes any exception to get thrown before object modification commences.
  • 33. public Object pop() {  if (size == 0)  throw new EmptyStackException();  Object result = elements[--size];  elements[size] = null; // Eliminate obsolete reference  return result;  }
  • 34. Another approach to achieving failure atomicity is to write recovery code that intercepts a failure that occurs in the midst of an operation and causes the object to roll back its state to the point before the operation began.  To achieve failure atomicity is to perform the operation on a temporary copy of the object and to replace the contents of the object with the temporary copy once the operation is complete.
  • 35.
  • 36. try {  ...  } catch (SomeException e) {  } The purpose of exceptions is defeated here.
  • 37. Pluggable exception handlers is a technique that allows the users of a component to customize the exception handling of that component. Instead of handling, enriching, wrapping and/or logging the exception, the exception handling is delegated to an exception handler.
  • 38. public interface ExceptionHandler  {  public void handle(Exception e, String errorMessage);  }
  • 39. public class WrappingHandler implements ExceptionHandler {  public void handle(Exception e, String message)  {  throw new RuntimeException(message, e);  }  }
  • 40. public class CollectingHandler implements ExceptionHandler  {  List exceptions = new ArrayList();  public List getExceptions()  {  return this.exceptions;  }  public void handle(Exception e, String message)  {  this.exceptions.add(e); //message is ignored here, but could //have been collected too.  }  }
  • 41. public class Component{  protected ExceptionHandler exceptionHandler = null;  public void setExceptionHandler(ExceptionHandler handler){ this.exceptionHandler = handler;  }  public void processFile(String fileName){  FileInputStream input = null;  try{  input = new FileInputStream(fileName); processStream(input);  }  catch (IOException e){  this.exceptionHandler.handle(e, "error processing file: " + fileName);  }  }  protected void processStream(InputStream input) throws IOException{  //do something with the stream.  }  }
  • 42. Pluggable exception handlers are most effective in situations where the exceptions occurring can be handled sensibly in different ways. For instance, when validating an XML document, or an HTML form, you may not always want to stop the validation at the first validation error. In some situations you might want to continue validation to catch all validation exceptions thrown, and show them all to the user at the same time. This saves the user from having to correct an error, validate, correct error, validate over and over again. All errors can be caught and corrected in one iteration.
  • 43. InputStream input = null; try{ input = new FileInputStream("myFile.txt"); //do something with the stream } catch(IOException e){ throw new AException(e); } finally { try{ input.close(); } catch(IOException e){ throw new BException(e); } }
  • 44. The last exception thrown in a try-catch-finally block is the exception that will be propagated up the call stack. All earlier exceptions will disappear.
  • 45. InputStream input = null;  try{  input = new FileInputStream("myFile.txt"); //do something with the stream  } catch(IOException e){  //first catch block  throw new WrapperException(e);  } finally {  try{  if(input != null) input.close();  } catch(IOException e){  //second catch block  throw new WrapperException(e);  }  }

Notes de l'éditeur

  1. Show demo