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

More Related Content

What's hot

Java Tokens
Java  TokensJava  Tokens
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
lalithambiga kamaraj
 
Files in java
Files in javaFiles in java
Applets
AppletsApplets
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Md. Tanvir Hossain
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
Shubham Dwivedi
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptionsmyrajendra
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
Surbhi Panhalkar
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
JavabynataraJ
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
arvind pandey
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
Spotle.ai
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
Exception handling
Exception handlingException handling
Exception handling
Tata Consultancy Services
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
garishma bhatia
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
VINOTH R
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 

What's hot (20)

Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Files in java
Files in javaFiles in java
Files in java
 
OOP java
OOP javaOOP java
OOP java
 
Applets
AppletsApplets
Applets
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java abstract class & abstract methods
Java abstract class & abstract methodsJava abstract class & abstract methods
Java abstract class & abstract methods
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Java threads
Java threadsJava threads
Java threads
 
Java-java virtual machine
Java-java virtual machineJava-java virtual machine
Java-java virtual machine
 
Java exception handling ppt
Java exception handling pptJava exception handling ppt
Java exception handling ppt
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java Data Types
Java Data TypesJava Data Types
Java Data Types
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
Exception handling
Exception handlingException handling
Exception handling
 
Constructor overloading & method overloading
Constructor overloading & method overloadingConstructor overloading & method overloading
Constructor overloading & method overloading
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 

Viewers also liked

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 HandlingPrabhdeep Singh
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
Tareq Hasan
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Pratik Soares
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11Terry 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.34myrajendra
 
Exception handling
Exception handlingException handling
Exception handlingIblesoft
 
Access Protection
Access ProtectionAccess Protection
Access Protectionmyrajendra
 
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
 

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
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Java: Exception
Java: ExceptionJava: Exception
Java: Exception
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
9781111530532 ppt ch11
9781111530532 ppt ch119781111530532 ppt ch11
9781111530532 ppt ch11
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
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
 
Real-time Programming in Java
Real-time Programming in JavaReal-time Programming in Java
Real-time Programming in Java
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Exception handling
Exception handlingException handling
Exception handling
 
Access Protection
Access ProtectionAccess Protection
Access Protection
 
Java exception
Java exception Java exception
Java exception
 
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
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error Handling
 
Improve business process with microservice integration
Improve business process with microservice integration �Improve business process with microservice integration �
Improve business process with microservice integration
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Exception handling in asp.net
Exception handling in asp.netException handling in asp.net
Exception handling in asp.net
 
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)
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Packages in java
Packages in javaPackages in java
Packages in java
 

Similar to Exceptions in Java

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 exceptionsSujit Kumar
 
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 Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
kashyapneha2809
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
nehakumari0xf
 
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
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
GaneshKumarKanthiah
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
sonalipatil225940
 

Similar to Exceptions in Java (20)

UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
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
 
Introduction to java exceptions
Introduction to java exceptionsIntroduction to java exceptions
Introduction to java exceptions
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Exception handling
Exception handlingException handling
Exception handling
 
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
 
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
 
Exception handling
Exception handlingException handling
Exception handling
 
Java Exceptions and Exception Handling
 Java  Exceptions and Exception Handling Java  Exceptions and Exception Handling
Java Exceptions and Exception Handling
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception HandlingException Handling Exception Handling Exception Handling
Exception Handling Exception Handling Exception Handling
 
Training material exceptions v1
Training material   exceptions v1Training material   exceptions v1
Training material exceptions v1
 
Exception
ExceptionException
Exception
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception handling in java-PPT.pptx
Exception handling in java-PPT.pptxException handling in java-PPT.pptx
Exception handling in java-PPT.pptx
 

Recently uploaded

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
DanBrown980551
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 

Recently uploaded (20)

LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 

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

  1. NPEDisk has been removedURL does not exist. Socket exception
  2. 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).
  3. 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.
  4. 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).
  5. Creating your own exception class
  6. 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!”); }}
  7. 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.
  8. 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.
  9. Do not use exceptions to manage flow of control: exit a loop with a status variable rather than raising an exception.