SlideShare a Scribd company logo
Exceptions in Java




                     Author: Vadim Lotar
                     Lohika (2011)
Agenda


 •   Introduction
 •   Errors and Error handling
 •   Exceptions
 •   Types of Exceptions
 •   Keywords
 •   Exceptions handling
 •   Summary
Introduction
 •   Customers have high expectations for the code we
     produce.
 •   Users will use our programs in unexpected ways.
 •   Due to design errors or coding errors, our
     programs may fail in unexpected ways during
     execution
 •   It is our responsibility to produce quality code that
     does not fail unexpectedly.
 •   Consequently, we must design error handling into
     our programs.
Errors and Error handling
 •   An Error is any unexpected result obtained from a
     program during execution.
 •   Unhandled errors may manifest themselves as
     incorrect results or behavior, or as abnormal
     program termination.
 •   Errors should
     be handled by
     the
     programmer, to
     prevent them
     from reaching
     the user.
Errors and Error handling
 •   Memory errors (i.e memory incorrectly allocated,
     memory leaks…)
 •   File system errors (i.e. disk is full…)
 •   Network errors (i.e. network is down…)
 •   Calculation errors (i.e. divide by 0)
 •   Array errors (i.e. accessing element –1)
 •   Conversion errors (i.e. convert „q‟ to a number)
 •   Can you think of some others?
Errors and Error handling
 •   Every method returns a value (flag)
     indicating either success, failure, or some
     error condition.
 •   Cons: developer must remember to
     always check the return value and take
     appropriate action.
 •   Where used: traditional programming
     languages (i.e. C) use this method for almost
     all library functions
Errors and Error handling
 •   Create a global error handling routine,
     and use some form of “jump” instruction
     to call this routine when an error occurs
 •   Cons: “jump” instruction (GoTo) are
     considered “bad programming practice”
     and are discouraged
 •   Where used: many older programming texts
     (C, FORTRAN) recommended this method to
     programmers.
Exceptions
Exceptions

 •   Exceptions – a better error handling
 •   What are they?
     •   An exception is a representation of an error
         condition or a situation that is not the
         expected result of a method.
     •   Exceptions are built into the Java language
         and are available to all program code.
     •   Exceptions isolate the code that deals with the
         error condition from regular program logic.
Types of Exceptions
•   Unchecked Exceptions                  •   Checked Exceptions
    It is not required that these types       Must either be caught by a
    of exceptions be caught or                method or declared in its
    declared on a method.                     signature.

    •   Runtime exceptions can be             •   Placing exceptions in the
        generated by methods or by                method signature harkens
        the JVM itself.                           back to a major concern for
                                                  Goodenough.
    •   Errors are generated from
        deep within the JVM, and              •   This requirement is viewed
        often indicate a truly fatal              with derision in the
        state.                                    hardcore C++ community.

    •   Runtime exceptions are a              •   A common technique for
        source of major controversy!              simplifying checked
                                                  exceptions is subsumption.
Types of Exceptions
  Throwable               The base class for all exceptions.



  Error                   Indicates serious problems that a reasonable application
                          should not try to catch. Most such errors are abnormal
                          conditions.
  Exception               Anything which should be handled by the invoker.




                                                java.lang.Throwable


    java.lang.Error                                               java.lang.Exception


 java.lang.ThreadDeath             java.lang.RuntimeException                                java.io.IOException


               java.lang.NullPointerException    java.lang.IllegalArgumentException     java.io.FileNotFoundException
Types of Exceptions

    •    Three Critical Decisions:
•   How do you decide to raise an exception rather than return?
        1. Is the situation truly out of the ordinary?
        2. Should it be impossible for the caller to ignore this problem?
        3. Does this situation render the class unstable or inconsistent?

•   Should you reuse an existing exception or create a new type?
        1. Can you map this to an existing exception class?
        2. Is the checked/unchecked status of mapped exception acceptable?
        3. Are you masking many possible exceptions for a more general one?

•   How do you deal with subsumption in a rich exception hierarchy?
        1. Avoid throwing a common base class (e.g. IOException).
        2. Never throw an instance of the Exception or Throwable classes.
Keywords
 •   throws
     Describes the exceptions which can be raised by a method.

 •   throw
     Raises an exception to the first available handler in the call
     stack, unwinding the stack along the way.

 •   try
     Marks the start of a block associated with a set of exception
     handlers.

 •   catch
     If the block enclosed by the try generates an exception of this
     type, control moves here; watch out for implicit subsumption.

 •   finally
     Always called when the try block concludes, and after any
     necessary catch handler is complete.
Keywords
 public void setProperty(String p_strValue) throws
    NullPointerException
 {
    if (p_strValue == null) {throw new NullPointerException(“...”);}
 }

 public void myMethod() {
    MyClass oClass = new MyClass();

     try {
       oClass.setProperty(“foo”);
       oClass.doSomeWork();

     } catch (NullPointerException npe) {
       System.err.println(“Unable to set property: “+npe.toString());
     } finally {
       oClass.cleanup();
     }
 }
Keywords
 •   throw(s)
 /* The IllegalArgumentException is considered unchecked, and
  * even making it part of the signature will not alter that. */
 public void setName(String p_strName) throws
    IllegalArgumentException
 {
    /* valid names cannot be zero length */
    if (p_strName.length() == 0) {
      throw new IllegalArgumentException(“…”);
    }
    m_strName = p_strName;
 }

 public void foo() {
    setName(“”); /* No warning about unhandled exceptions. */
 }
Keywords
 •   throw(s)
 /* Make a bad parameter exception class */
 class NuttyParameterException extends Exception { … }

 /* To really make an invoker pay attention, use a checked
  * exception type rather than a Runtime Exception type, but you
    must declare that you will throw the type! */
 public void setName(String p_strName)
                                 throws NuttyParameterException
 {
    /* valid names cannot be zero length */
    if (p_strName == null || p_strName.length() == 0) {
      throw new NuttyParameterException(“…”);
    }
    m_strName = p_strName;
 }
 /* Many of us will have an unquenchable desire to use a Runtime
  * exception in the above, but resist! */
 public void foo() {
    setName(“”); /* This does result in an error. */
 }
Keywords
 •   try
 /* The try statement marks the position of the first bytecode
    instruction
  * protected by an exception handler. */
 try {
    UserRecord oUser = new UserRecord();
    oUser.setName(“Mr. XXX”);
    oUser.store();

 /* This catch statement then marks the final bytecode
    instruction protected, and begins the list of exceptions
    handled. This info is collected and is stored in the
    exception table for the method. */
 } catch (CreateException ce) {
    System.err.println(“Unable to create user record in the
    database.”);
 }
Keywords
 •   catch
 /* A simple use of a catch block is to catch the exception
    raised by the code from a prior slide. */
 try {
    myObject.setName(“foo”);
 } catch (NuttyParameterException npe) {
    System.err.println(“Unable to assign name: “ +
    npe.toString());
 }

 try { /* example 2 */
    myObject.setName(“foo”);
 } catch (NuttyParameterException npe) { /* log and relay this
    problem. */
    System.err.println(“Unable to assign name: “ +
    npe.toString());
    throw npe;
 }
Keywords
 •   catch
 /* Several catch blocks of differing types can be concatenated.
    */
  try {
    URL myURL = new URL("http://www.mainejug.org");
    InputStream oStream = myURL.openStream();
    byte[] myBuffer = new byte[512];
    int nCount = 0;

     while ((nCount = oStream.read(myBuffer)) != -1) {
       System.out.println(new String(myBuffer, 0, nCount));
     }
     oStream.close();

 } catch (MalformedURLException mue) {
    System.err.println("MUE: " + mue.toString());
 } catch (IOException ioe) {
    System.err.println("IOE: " + ioe.toString());
 }
Keywords
 •   finally
 URL myURL = null;
 InputStream oStream = null;
 /* The prior sample completely neglected to discard the network
  * resources, remember that the GC is non-determinstic!! */
 try {
    /* Imagine you can see the code from the last slide here...
    */

 } finally { /* What two things can cause a finally block to be
    missed? */
    /* Since we cannot know when the exception occurred, be
    careful! */
      try {
         oStream.close();
      } catch (Exception e) {
    }
 }
Keywords
 •   finally
 public boolean anotherMethod(Object myParameter) {

     try { /* What value does this snippet return? */
       myClass.myMethod(myParameter);
       return true;

     } catch (Exception e) {
       System.err.println(“Exception in anotherMethod()“
                                         +e.toString());
       return false;

     } finally {
       /* If the close operation can raise an exception,
       whoops! */
       if (myClass.close() == false) {
              break;
       }                                             1. True
     }                                               2. False
     return false;
 }
                                                      3. An exception
                                                      4. Non of above
Keywords
 •   finally
 public void callMethodSafely() {

     while (true) { /* How about this situation? */
       try {
              /* Call this method until it returns false.
              */
              if (callThisOTherMethod() == false) {
                     return;
              }

       } finally {                                 1.   Infinite loop
              continue;                            2.   1
       }                                           3.   2
     } /* end of while */                          4.   An exception
 }

 public boolean callThisOTherMethod() {
    return false;
 }
Practice
 /* Since UnknownHostException extends IOException, the
    catch block associated with the former is subsumed. */
 try {
    Socket oConn = new Socket(“www.sun.com”, 80);
 } catch (IOException ioe) {
 } catch (UnknownHostException ohe) {
 }




 /* The correct structure is to arrange the catch blocks
    with the most derived class first, and base class at
    the bottom. */
 try {
    Socket oConn = new Socket(“www.sun.com”, 80);
 } catch (UnknownHostException ohe) {
 } catch (IOException ioe) {
 }
Practice
 class MyThread implements Runnable {
    public MyTask m_oTask = null;
    public void run() {
      if (m_oTask == null) {
        throw new IllegalStateException(“No work to be
    performed!”);
      } else {
        /* Do the work of the thread. */
      }
    }
 }

 public void foo() {
    MyThread oThread = new MyThread();
    /* There is no way to get the exception from the run()
    method! */
    new Thread(oThread).start();
    /* Good reason for Runtime choice!! */
 }
Practice
 public interface ITest {
     void test() throws IOException ;
 }

 public class TestImpl implements ITest{

     public void test() throws IOException, InvalidArgumentException {
        //some code
     }

     public void test() throws IOException, FileNotFoundException {
        //some code
     }

     public void test() {
        //some code
     }

     public void test() throws IOException {
        //some code
     }
 }
New in Java 7
} catch (FirstException ex) {           Multi-catch feature
    logger.error(ex);                   } catch (FirstException | SecondException ex) {
    throw ex;                               logger.error(ex);
} catch (SecondException ex) {              throw ex;
    logger.error(ex);                   }
    throw ex;
}


Final rethrow
public static void test2() throws ParseException, IOException{
  DateFormat df = new SimpleDateFormat("yyyyMMdd");
  try {
     df.parse("x20110731");
     new FileReader("file.txt").read();
  } catch (final Exception e) {
     System.out.println("Caught exception: " + e.getMessage());
     throw e;
  }
}
New in Java 7
 public class OldTry {
      public static void main(String[] args) {
         OldResource res = null;
         try {
             res = new OldResource();
             res.doSomeWork("Writing an article");
         } catch (Exception e) {
             System.out.println("Exception Message: " +
                   e.getMessage() + " Exception Type: " + e.getClass().getName());
         } finally {
             try {
                res.close();
             } catch (Exception e) {
                System.out.println("Exception Message: " +
                      e.getMessage() + " Exception Type: " + e.getClass().getName());
             }
         }
      }
   }

 public class TryWithRes {
     public static void main(String[] args) {
         try(NewResource res = new NewResource("Res1 closing")){
             res.doSomeWork("Listening to podcast");
         } catch(Exception e){
             System.out.println("Exception: "+
        e.getMessage()+" Thrown by: "+e.getClass().getSimpleName());
         }
     }
 }
Summary

 •   Exceptions are a powerful error
     handling mechanism.


 •   Exceptions in Java are built into the
     language.


 •   Exceptions can be handled by the
     programmer (try-catch), or handled by
     the Java environment (throws).
Q&A
Task
 •   Implement Application
     •   App takes two parameters from the command
         line: the directory path and a file name.
     •   App should have an ability to find the file in
         sub folders too.
     •   Read data from file and print it
     •   Every possible error situation should be
         handled
         •   Create an own class which represents an
             exception
Ad

More Related Content

What's hot (20)

Java program structure
Java program structureJava program structure
Java program structure
shalinikarunakaran1
 
Operators in java
Operators in javaOperators in java
Operators in java
Then Murugeshwari
 
Generics in java
Generics in javaGenerics in java
Generics in java
suraj pandey
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
VINOTH R
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
myrajendra
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
Ankita Totala
 
Control flow statements in java
Control flow statements in javaControl flow statements in java
Control flow statements in java
yugandhar vadlamudi
 
Applets
AppletsApplets
Applets
Prabhakaran V M
 
Features of java
Features of javaFeatures of java
Features of java
WILLFREDJOSE W
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
Java IO
Java IOJava IO
Java IO
UTSAB NEUPANE
 
JDBC – Java Database Connectivity
JDBC – Java Database ConnectivityJDBC – Java Database Connectivity
JDBC – Java Database Connectivity
Information Technology
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
Raja Sekhar
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
Lovely Professional University
 
Java package
Java packageJava package
Java package
CS_GDRCST
 
Swing and AWT in java
Swing and AWT in javaSwing and AWT in java
Swing and AWT in java
Adil Mehmoood
 
Java Streams
Java StreamsJava Streams
Java Streams
M Vishnuvardhan Reddy
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 

Viewers also liked (20)

Log management (elk) for spring boot application
Log management (elk) for spring boot applicationLog management (elk) for spring boot application
Log management (elk) for spring boot application
Vadym Lotar
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11
Terry Yoast
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
talha ijaz
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 
Real-time Programming in Java
Real-time Programming in JavaReal-time Programming in Java
Real-time Programming in Java
Aleš Plšek
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
myrajendra
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Access Protection
Access ProtectionAccess Protection
Access Protection
myrajendra
 
Java exception
Java exception Java exception
Java exception
Arati Gadgil
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error Handling
Christina Lin
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration
Christina Lin
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
Neelesh Shukla
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Log management (elk) for spring boot application
Log management (elk) for spring boot applicationLog management (elk) for spring boot application
Log management (elk) for spring boot application
Vadym Lotar
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
Prabhdeep Singh
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11
Terry Yoast
 
7 streams and error handling in java
7 streams and error handling in java7 streams and error handling in java
7 streams and error handling in java
Jyoti Verma
 
Real-time Programming in Java
Real-time Programming in JavaReal-time Programming in Java
Real-time Programming in Java
Aleš Plšek
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
myrajendra
 
Exception handling
Exception handlingException handling
Exception handling
Iblesoft
 
Access Protection
Access ProtectionAccess Protection
Access Protection
myrajendra
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
İbrahim Kürce
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error Handling
Christina Lin
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration
Christina Lin
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
ankitgarg_er
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
Neelesh Shukla
 
Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)Exception handling & logging in Java - Best Practices (Updated)
Exception handling & logging in Java - Best Practices (Updated)
Angelin R
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
BHUVIJAYAVELU
 
Ad

Similar to Exceptions in Java (20)

UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
Sujit Kumar
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptxusing Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Exception handling
Exception handlingException handling
Exception handling
Karthik Sekar
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
baabtra.com - No. 1 supplier of quality freshers
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
Exception
ExceptionException
Exception
abhay singh
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 
Ch-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for allCh-1_5.pdf this is java tutorials for all
Ch-1_5.pdf this is java tutorials for all
HayomeTakele
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
Sujit Kumar
 
using Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptxusing Java Exception Handling in Java.pptx
using Java Exception Handling in Java.pptx
AshokRachapalli1
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
Bharath K
 
Exception handling
Exception handlingException handling
Exception handling
pooja kumari
 
unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025unit 4 msbte syallbus for sem 4 2024-2025
unit 4 msbte syallbus for sem 4 2024-2025
AKSHAYBHABAD5
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
MaqdamYasir
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
AboMohammad10
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
Shinu Suresh
 
Ad

Recently uploaded (20)

AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
Transcript: #StandardsGoals for 2025: Standards & certification roundup - Tec...
BookNet Canada
 
How analogue intelligence complements AI
How analogue intelligence complements AIHow analogue intelligence complements AI
How analogue intelligence complements AI
Paul Rowe
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 

Exceptions in Java

  • 1. Exceptions in Java Author: Vadim Lotar Lohika (2011)
  • 2. Agenda • Introduction • Errors and Error handling • Exceptions • Types of Exceptions • Keywords • Exceptions handling • Summary
  • 3. Introduction • Customers have high expectations for the code we produce. • Users will use our programs in unexpected ways. • Due to design errors or coding errors, our programs may fail in unexpected ways during execution • It is our responsibility to produce quality code that does not fail unexpectedly. • Consequently, we must design error handling into our programs.
  • 4. Errors and Error handling • An Error is any unexpected result obtained from a program during execution. • Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. • Errors should be handled by the programmer, to prevent them from reaching the user.
  • 5. Errors and Error handling • Memory errors (i.e memory incorrectly allocated, memory leaks…) • File system errors (i.e. disk is full…) • Network errors (i.e. network is down…) • Calculation errors (i.e. divide by 0) • Array errors (i.e. accessing element –1) • Conversion errors (i.e. convert „q‟ to a number) • Can you think of some others?
  • 6. Errors and Error handling • Every method returns a value (flag) indicating either success, failure, or some error condition. • Cons: developer must remember to always check the return value and take appropriate action. • Where used: traditional programming languages (i.e. C) use this method for almost all library functions
  • 7. Errors and Error handling • Create a global error handling routine, and use some form of “jump” instruction to call this routine when an error occurs • Cons: “jump” instruction (GoTo) are considered “bad programming practice” and are discouraged • Where used: many older programming texts (C, FORTRAN) recommended this method to programmers.
  • 9. Exceptions • Exceptions – a better error handling • What are they? • An exception is a representation of an error condition or a situation that is not the expected result of a method. • Exceptions are built into the Java language and are available to all program code. • Exceptions isolate the code that deals with the error condition from regular program logic.
  • 10. Types of Exceptions • Unchecked Exceptions • Checked Exceptions It is not required that these types Must either be caught by a of exceptions be caught or method or declared in its declared on a method. signature. • Runtime exceptions can be • Placing exceptions in the generated by methods or by method signature harkens the JVM itself. back to a major concern for Goodenough. • Errors are generated from deep within the JVM, and • This requirement is viewed often indicate a truly fatal with derision in the state. hardcore C++ community. • Runtime exceptions are a • A common technique for source of major controversy! simplifying checked exceptions is subsumption.
  • 11. Types of Exceptions Throwable The base class for all exceptions. Error Indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Exception Anything which should be handled by the invoker. java.lang.Throwable java.lang.Error java.lang.Exception java.lang.ThreadDeath java.lang.RuntimeException java.io.IOException java.lang.NullPointerException java.lang.IllegalArgumentException java.io.FileNotFoundException
  • 12. Types of Exceptions • Three Critical Decisions: • How do you decide to raise an exception rather than return? 1. Is the situation truly out of the ordinary? 2. Should it be impossible for the caller to ignore this problem? 3. Does this situation render the class unstable or inconsistent? • Should you reuse an existing exception or create a new type? 1. Can you map this to an existing exception class? 2. Is the checked/unchecked status of mapped exception acceptable? 3. Are you masking many possible exceptions for a more general one? • How do you deal with subsumption in a rich exception hierarchy? 1. Avoid throwing a common base class (e.g. IOException). 2. Never throw an instance of the Exception or Throwable classes.
  • 13. Keywords • throws Describes the exceptions which can be raised by a method. • throw Raises an exception to the first available handler in the call stack, unwinding the stack along the way. • try Marks the start of a block associated with a set of exception handlers. • catch If the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption. • finally Always called when the try block concludes, and after any necessary catch handler is complete.
  • 14. Keywords public void setProperty(String p_strValue) throws NullPointerException { if (p_strValue == null) {throw new NullPointerException(“...”);} } public void myMethod() { MyClass oClass = new MyClass(); try { oClass.setProperty(“foo”); oClass.doSomeWork(); } catch (NullPointerException npe) { System.err.println(“Unable to set property: “+npe.toString()); } finally { oClass.cleanup(); } }
  • 15. Keywords • throw(s) /* The IllegalArgumentException is considered unchecked, and * even making it part of the signature will not alter that. */ public void setName(String p_strName) throws IllegalArgumentException { /* valid names cannot be zero length */ if (p_strName.length() == 0) { throw new IllegalArgumentException(“…”); } m_strName = p_strName; } public void foo() { setName(“”); /* No warning about unhandled exceptions. */ }
  • 16. Keywords • throw(s) /* Make a bad parameter exception class */ class NuttyParameterException extends Exception { … } /* To really make an invoker pay attention, use a checked * exception type rather than a Runtime Exception type, but you must declare that you will throw the type! */ public void setName(String p_strName) throws NuttyParameterException { /* valid names cannot be zero length */ if (p_strName == null || p_strName.length() == 0) { throw new NuttyParameterException(“…”); } m_strName = p_strName; } /* Many of us will have an unquenchable desire to use a Runtime * exception in the above, but resist! */ public void foo() { setName(“”); /* This does result in an error. */ }
  • 17. Keywords • try /* The try statement marks the position of the first bytecode instruction * protected by an exception handler. */ try { UserRecord oUser = new UserRecord(); oUser.setName(“Mr. XXX”); oUser.store(); /* This catch statement then marks the final bytecode instruction protected, and begins the list of exceptions handled. This info is collected and is stored in the exception table for the method. */ } catch (CreateException ce) { System.err.println(“Unable to create user record in the database.”); }
  • 18. Keywords • catch /* A simple use of a catch block is to catch the exception raised by the code from a prior slide. */ try { myObject.setName(“foo”); } catch (NuttyParameterException npe) { System.err.println(“Unable to assign name: “ + npe.toString()); } try { /* example 2 */ myObject.setName(“foo”); } catch (NuttyParameterException npe) { /* log and relay this problem. */ System.err.println(“Unable to assign name: “ + npe.toString()); throw npe; }
  • 19. Keywords • catch /* Several catch blocks of differing types can be concatenated. */ try { URL myURL = new URL("http://www.mainejug.org"); InputStream oStream = myURL.openStream(); byte[] myBuffer = new byte[512]; int nCount = 0; while ((nCount = oStream.read(myBuffer)) != -1) { System.out.println(new String(myBuffer, 0, nCount)); } oStream.close(); } catch (MalformedURLException mue) { System.err.println("MUE: " + mue.toString()); } catch (IOException ioe) { System.err.println("IOE: " + ioe.toString()); }
  • 20. Keywords • finally URL myURL = null; InputStream oStream = null; /* The prior sample completely neglected to discard the network * resources, remember that the GC is non-determinstic!! */ try { /* Imagine you can see the code from the last slide here... */ } finally { /* What two things can cause a finally block to be missed? */ /* Since we cannot know when the exception occurred, be careful! */ try { oStream.close(); } catch (Exception e) { } }
  • 21. Keywords • finally public boolean anotherMethod(Object myParameter) { try { /* What value does this snippet return? */ myClass.myMethod(myParameter); return true; } catch (Exception e) { System.err.println(“Exception in anotherMethod()“ +e.toString()); return false; } finally { /* If the close operation can raise an exception, whoops! */ if (myClass.close() == false) { break; } 1. True } 2. False return false; } 3. An exception 4. Non of above
  • 22. Keywords • finally public void callMethodSafely() { while (true) { /* How about this situation? */ try { /* Call this method until it returns false. */ if (callThisOTherMethod() == false) { return; } } finally { 1. Infinite loop continue; 2. 1 } 3. 2 } /* end of while */ 4. An exception } public boolean callThisOTherMethod() { return false; }
  • 23. Practice /* Since UnknownHostException extends IOException, the catch block associated with the former is subsumed. */ try { Socket oConn = new Socket(“www.sun.com”, 80); } catch (IOException ioe) { } catch (UnknownHostException ohe) { } /* The correct structure is to arrange the catch blocks with the most derived class first, and base class at the bottom. */ try { Socket oConn = new Socket(“www.sun.com”, 80); } catch (UnknownHostException ohe) { } catch (IOException ioe) { }
  • 24. Practice class MyThread implements Runnable { public MyTask m_oTask = null; public void run() { if (m_oTask == null) { throw new IllegalStateException(“No work to be performed!”); } else { /* Do the work of the thread. */ } } } public void foo() { MyThread oThread = new MyThread(); /* There is no way to get the exception from the run() method! */ new Thread(oThread).start(); /* Good reason for Runtime choice!! */ }
  • 25. Practice public interface ITest { void test() throws IOException ; } public class TestImpl implements ITest{ public void test() throws IOException, InvalidArgumentException { //some code } public void test() throws IOException, FileNotFoundException { //some code } public void test() { //some code } public void test() throws IOException { //some code } }
  • 26. New in Java 7 } catch (FirstException ex) { Multi-catch feature logger.error(ex); } catch (FirstException | SecondException ex) { throw ex; logger.error(ex); } catch (SecondException ex) { throw ex; logger.error(ex); } throw ex; } Final rethrow public static void test2() throws ParseException, IOException{ DateFormat df = new SimpleDateFormat("yyyyMMdd"); try { df.parse("x20110731"); new FileReader("file.txt").read(); } catch (final Exception e) { System.out.println("Caught exception: " + e.getMessage()); throw e; } }
  • 27. New in Java 7 public class OldTry { public static void main(String[] args) { OldResource res = null; try { res = new OldResource(); res.doSomeWork("Writing an article"); } catch (Exception e) { System.out.println("Exception Message: " + e.getMessage() + " Exception Type: " + e.getClass().getName()); } finally { try { res.close(); } catch (Exception e) { System.out.println("Exception Message: " + e.getMessage() + " Exception Type: " + e.getClass().getName()); } } } } public class TryWithRes { public static void main(String[] args) { try(NewResource res = new NewResource("Res1 closing")){ res.doSomeWork("Listening to podcast"); } catch(Exception e){ System.out.println("Exception: "+ e.getMessage()+" Thrown by: "+e.getClass().getSimpleName()); } } }
  • 28. Summary • Exceptions are a powerful error handling mechanism. • Exceptions in Java are built into the language. • Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws).
  • 29. Q&A
  • 30. Task • Implement Application • App takes two parameters from the command line: the directory path and a file name. • App should have an ability to find the file in sub folders too. • Read data from file and print it • Every possible error situation should be handled • Create an own class which represents an exception

Editor's Notes

  • #6: NPEDisk has been removedURL does not exist. Socket exception
  • #8: Once you jump to the error routine, you cannot return to the point of origin and so must (probably) exit the program.Those who use this method will frequently adapt it to new languages (C++, Java).
  • #10: Exceptions are a mechanism that provides the best of both worlds.Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error.Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.
  • #11: How are they used?Exceptions fall into two categories:Checked ExceptionsUnchecked ExceptionsChecked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered “non fatal” to program executionChecked exceptions must be handled in your code, or passed to parent classes for handling.How are they used?Unchecked exceptions represent error conditions that are considered “fatal” to program execution.You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error messageExamples:Checked exceptions include errors such as “array index out of bounds”, “file not found” and “number format conversion”.Unchecked exceptions include errors such as “null pointer”.Runtime exceptions make it impossible to know what exceptions can be emitted by a method. They also result in incosistent throws decls among developers.Describe subsumption to people: subsumption is often how IOException derivatives are dealt with (subsumption is casting to the base class).The most vituperative debate is between those who believe unchecked exceptions make mechanical testing nearly impossible, and those who believe that checked exceptions impinge on polymorphism by making the exception list part of the method signature (and thereby inheritable).
  • #12: Creating your own exception class
  • #13: Creating your own exception classWhen you attempt to map your situation onto an existing Exception class consider these suggestions:Avoid using an unchecked exception, if it is important enough to explicitly throw, it is important enough to be caught.Never throw a base exception class if you can avoid it: RuntimeException, IOException, RemoteException, etc.Be certain your semantics really match. For example, javax.transaction.TransactionRolledBackException, should not be raised by your JDBC code.There is no situation which should cause you to throw the Exception or Throwable base classes. Never.Use unchecked exceptions to indicate a broken contract:public void setName(String p_strName) { /* This is a violated precondition. */ if (p_strName == null || p_strName.length() == 0) { throw new InvalidArgumentException(“Name parameter invalid!”); }}
  • #27: Using the final keyword it allows you to throw an exception of the exact dynamic type that will be throwed. So if an IOException occurs, an IOException will be throwed. Of course, you have to declare the exceptions not caught. You throws clauses will exactly the same if you use the code (in //some code) without catching anything but now you can do something if that happens.I think multi-catch is a great feature, but for me the final rethrow is not often useful for programmers and perhaps a little weird using the final keyword.
  • #28: Using the final keyword it allows you to throw an exception of the exact dynamic type that will be throwed. So if an IOException occurs, an IOException will be throwed. Of course, you have to declare the exceptions not caught. You throws clauses will exactly the same if you use the code (in //some code) without catching anything but now you can do something if that happens.I think multi-catch is a great feature, but for me the final rethrow is not often useful for programmers and perhaps a little weird using the final keyword.
  • #29: Do not use exceptions to manage flow of control: exit a loop with a status variable rather than raising an exception.