SlideShare une entreprise Scribd logo
1  sur  63
Event Handling and Exceptions
The process of responding to an
event. Window programs are
said to be event-driven because
they operate by performing
actions in response to events.
Contents

  The Delegation Event Model
  Event Classes
  Event Listeners
  Adapter Classes
  Inner Classes
  Anonymous Inner Classes
The Delegation Event Model
Applet is event-driven.
Delegation Event model: JDK 1.1 introduced
Event Classes
Event Classes
Event Listeners
Adapter Classes
Delegated Event Model
Inner Classes
Anonymous Inner Classes
Exception in Java are classified
on the basis of the exception
handled by the java compiler.
Contents:

   •Exception Handling in Java
       I.     Introduction
       II.    Common Exceptions
       III.   “Catching” Exceptions
       IV.    The Throwable Superclass
       V.     Effectively using try-catch
       VI.    Final thoughts of Exceptions

   •Type of Built-In Exceptions
       I.     Checked Exception
       II.    Unchecked Exception

   •Exception Hierarchy
Contents:

•Exceptions Methods
•Catching Exceptions
•Multiple Catch blocks
•The throws/throw keywords
•The Finally keywords
•Declaring your own exception
•Java Exceptions
Exception Handling in Java

I.        Introduction

             An exception is an error thrown by a class or method
     reporting an error in operation. For example, dividing by zero
     is undefined in mathematics, and a calculation can fail if this
     winds up being the case because of an error in user input. In
     this particular case an ArithmeticException is thrown, and
     unless the programmer looks for this exception and manually
     puts in code to handle it, the program will crash stating the
     exception thrown and a stack trace, which would be unhelpful
     to a casual user of a Java program. If the programmer handles
     the exception, he could deliver a useful error to the user and
     return the user to the beginning of the program so that they
     could continue to use it.
Exception Handling in Java

II.     Common Exceptions


      There are many different exceptions that can be thrown by a
      program, and the Java API contains quite a few. A lot are
      contained in the default package, java.lang; however, when
      you start using more functionality such as
      AWT, Swing, or java.io, the packages may also contain
      additional exceptions thrown by those libraries. As you start
      expanding the functionality, it might be a good idea to look
      at potential exceptions in the package and when they might
      be thrown in the course of your application.
Exception Handling in Java

II.    Common Exceptions

      Here is a primer of some:

      ArithmeticException--thrown if a program attempts to
      perform division by zero
      ArrayIndexOutOfBoundsException--thrown if a program
      attempts to access an index of an array that does not exist
      StringIndexOutOfBoundsException--thrown if a program
      attempts to access a character at a non-existent index in
      a String
      NullPointerException--thrown if the JVM attempts to
      perform an operation on an Object that points to no
      data, or null
                                        Continuation:
Exception Handling in Java

II.     Common Exceptions

      NumberFormatException--thrown if a program is
      attempting to convert a string to a numerical datatype, and
      the string contains inappropriate characters (i.e. 'z' or 'Q')
      ClassNotFoundException--thrown if a program can not find
      a class it depends at runtime (i.e., the class's ".class" file
      cannot be found or was removed from the CLASSPATH)
      IOException--actually contained in java.io, but it is thrown if
      the JVM failed to open an I/O stream
              As I said before, many different exceptions exist, and
      you should probably use your API documentation to learn
      about additional exceptions that may apply to your
      particular application.
                                         Continuation:
Exception Handling in Java

III.    “Catching”   Exceptions
       The java language contains keywords used specifically for
       testing for and handling exceptions. The ones we will be
       using here are try and catch, and they must be used in
       conjunction with one another. They sort of work like if-else:
       try{
        /*
          Contains code to be tested
        */
       }catch(Exception e){
        /*
          Contains code to be executed if instanced of Exception is
       caught
        */}
Exception Handling in Java

III.    “Catching”   Exceptions

       The catch statement can look for all exceptions, using
       the Exception superclass, or it can catch a specific
       exception that you think could be thrown in the code you
       are testing with the tryblock. You can even have
       multiple catch blocks to catch and execute custom code for
       a number of different errors. A good thing to note would be
       that any particular exception that is caught is compared
       with each catch statement sequentially; so it is a good idea
       to put more generic exceptions, like Exception, towards the
       bottom of the list.


                                         Continuation:
Exception Handling in Java

IV.    The Throwable Superclass

      The catch statement also stores an instance of the exception
      that was caught in the variable that the programmer uses, in
      the previous example Exception e. While all exceptions are
      subclasses of Exception, Exception itself is a subclass
      of Throwable, which contains a nice suite of methods that
      you can use to get all kinds of information to report about
      your exceptions:
      •getMessage()--returns the error message reported by the
      exception in a String
      •printStackTrace()--prints the stack trace of the exception to
      standard output, useful for debugging purposes in locating
      where the exception occurred
Exception Handling in Java

IV.     The Throwable Superclass


      •printStackTrace(PrintStream s)--prints the stack trace to an
      alternative output stream
      •printStackTrace(PrintWriter s)--prints the stack trace to a
      file, this way you can log stack traces transparent to the user
      or log for later reference
      •toString()--if you just decide to print out the exception it
      will print out this: NAME_OF_EXCEPTION: getMessage().

      Using the catch you now have control over what the error
      message is and where it goes.

                                         Continuation:
Exception Handling in Java

V.    Effectively using try-catch


     In this section, I'm going to give you a few code samples on
     using try-catch blocks to give you an idea of the flexibility
     you as a programmer have over exceptions in your programs.
     The scenario is a user has input a file name to a program of a
     file that does not exist. In this scenario we are going to be
     using a text-based program; however, in a graphical
     environment you can easily use the catch block to draw
     dialog boxes. In the first example, we want to print a useful
     error message and exit the program gracefully, saving the
     user from the confusing stack trace with something useful:
Exception Handling in Java

V.    Effectively using try-catch


     try{
       BufferedReader in = new BufferedReader(new
     FileReader(userInput));
       System.out.println(in.readLine())
     }catch(IOException e){
       System.err.println(e.getMessage());
       System.err.println("Error: " + userInput + " is not a valid
     file. Please verify that the file exists and that you have access
     to it.");
       System.exit(1);
     }
                                       Continuation:
Exception Handling in Java

V.    Effectively using try-catch


     Here, System.err.println() prints the error message
     to standard error output which is a high priority buffer
     that is used to report error messages to the console. If you're
     being a good programmer, you have separate methods that
     handle the different functionality of your programs; this way
     you can easily start the program from a previous place in the
     program before an exception occurs. In this next
     example, the user inputs the filename through the
     function getUserInput() elsewhere in the program; we want
     to report the "helpful error message" to the user and return
     the user to a place where he can enter a new filename.
                                       Continuation:
Exception Handling in Java

V.    Effectively using try-catch


       try{
        BufferedReader in = new BufferedReader(new
     FileReader(userInput));
        return in.readLine();
       }catch(IOException e){
        System.err.println(e.getMessage());
        System.err.println("Error: " + userInput + " is not a valid
     file. Please verify that the file exists and that you have access
     to it.");
        return getFileInput(getUserInput());
     }
                                       Continuation:
Exception Handling in Java

V.     Effectively using try-catch



      Now you have an idea of how you can control your
     programs once an exception is thrown, and this should give
     you the basic idea of how to work with exceptions in the Java
     language.




                                        Continuation:
Exception Handling in Java

VI.    Final thoughts of Exceptions



      The best way to prevent your application from crashing from
      exceptions is to avoid exceptions in the first place. It is much
      more costly for a system to catch and handle exceptions
      than to account for potential errors directly in your code. A
      lot of times, an exception can point to a problem in the
      programmer's logic rather than in the user's use of the
      program. You should look for the cause of exceptions, and
      try to understand why it occurred and make sure that you
      really had considered everything. You will be making far
      more resilient and robust applications.
                                        Continuation:
Types of Built In Exception


I. Checked Exception

These exception are the object of the Exception class or
any of its subclasses except Runtime Exception class.
These condition arises due to invalid input, problem
with your network connectivity and problem in
database.java.io.IOException is a checked exception.
This exception is thrown when there is an error in
input-output operation. In this case operation is
normally terminated.
Types of Built In Exception


List of Checked Exceptions

 Exception                                     Reason for Exception




                                              This Exception occurs when Java run-time system fail to find the
ClassNotFoundException
                                              specified class mentioned in the program




                                              This Exception occurs when you create an object of an abstract
Instantiation Exception
                                              class and interface




                                              This Exception occurs when you create an object of an abstract
Illegal Access Exception
                                              class and interface




                                              This Exception occurs when the method you call does not exist in
Not Such Method Exception
                                              class
Types of Built In Exception


II. Unchecked Exception



These Exception arises during run-time ,that occur due
to invalid argument passed to method. The java
Compiler does not check the program error during
compilation.
For Example when you divide a number by zero, run-
time exception is raised.
Types of Built In Exception


 List of Unchecked Exceptions
 Exception                                       Reason for Exception
                                               These Exception occurs, when you divide a number by zero
Arithmetic Exception
                                               causes an Arithmetic Exception
                                               These Exception occurs, when you try to assign a reference
Class Cast Exception                           variable of a class to an incompatible reference variable of
                                               another class

                                               These Exception occurs, when you assign an array which is not
Array Store Exception
                                               compatible with the data type of that array


                                               These Exception occurs, when you assign an array which is not
Array Index Out Of Bounds Exception
                                               compatible with the data type of that array


                                               These Exception occurs, when you try to implement an application
Null Pointer Exception
                                               without referencing the object and allocating to a memory

                                               These Exception occurs, when you try to convert a string variable
Number Format Exception                        in an incorrect format to integer (numeric format) that is not
                                               compatible with each other

Negative ArraySizeException                    These are Exception, when you declare an array of negative size.
An exception is a problem that arises during the execution of a program. An
exception can occur for many different reasons, including the following:
     •    A user has entered invalid data.
     •    A file that needs to be opened cannot be found.
     •    A network connection has been lost in the middle of
     communications, or the JVM has run out of memory.
Some of these exceptions are caused by user error, others by programmer
error, and others by physical resources that have failed in some manner.
•    Checked exceptions: A checked exception is an exception that is
typically a user error or a problem that cannot be foreseen by the
programmer. For example, if a file is to be opened, but the file cannot be
found, an exception occurs. These exceptions cannot simply be ignored
at the time of compilation.
•    Runtime exceptions: A runtime exception is an exception that
occurs that probably could have been avoided by the programmer. As
opposed to checked exceptions, runtime exceptions are ignored at the
time of compliation.
•    Errors: These are not exceptions at all, but problems that arise
beyond the control of the user or the programmer. Errors are typically
ignored in your code because you can rarely do anything about an error.
For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
All exception classes are subtypes of the java.lang.Exception class. The exception
class is a subclass of the Throwable class. Other than the exception class there is
another subclass called Error which is derived from the Throwable class.
Errors are not normally trapped form the Java programs. These conditions
normally happen in case of severe failures, which are not handled by the java
programs. Errors are generated to indicate errors generated by the runtime
environment. Example : JVM is out of Memory. Normally programs cannot
recover from errors.
The Exception class has two main subclasses : IOException class and
RuntimeException Class.
SN                                              Methods with Description

1    public String getMessage()
     Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable
     constructor.

2    public Throwable getCause()
     Returns the cause of the exception as represented by a Throwable object.


3    public String toString()
     Returns the name of the class concatenated with the result of getMessage()


4    public void printStackTrace()
     Prints the result of toString() along with the stack trace to System.err, the error output stream.


5    public StackTraceElement [] getStackTrace()
     Returns an array containing each element on the stack trace. The element at index 0 represents the top of the
     call stack, and the last element in the array represents the method at the bottom of the call stack.


6    public Throwable fillInStackTrace()
     Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in
     the stack trace.
A method catches an exception using a combination of
the try and catch keywords. A try/catch block is placed around the code that
might generate an exception. Code within a try/catch block is referred to as
protected code, and the syntax for using try/catch looks like the following:

                        try
                        {
                           //Protected code
                        }catch(ExceptionName e1)
                        {
                           //Catch block
                        }

     A catch statement involves declaring the type of exception you are trying to
catch. If an exception occurs in protected code, the catch block (or blocks) that
follows the try is checked. If the type of exception that occurred is listed in a
catch block, the exception is passed to the catch block much as an argument is
passed into a method parameter.
The following is an array is declared with 2 elements. Then the code tries
E   to access the 3rd element of the array which throws an exception.

        // File Name : ExcepTest.java
X       import java.io.*;
        public class ExcepTest{

A          public static void main(String args[]){
              try{
                 int a[] = new int[2];
M                System.out.println("Access element three :" + a[3]);
              }catch(ArrayIndexOutOfBoundsException e){

P             }
                 System.out.println("Exception thrown :" + e);

              System.out.println("Out of the block");
L       }
           }


E   This would produce following result:
        Exception thrown    :java.lang.ArrayIndexOutOfBoundsException: 3
        Out of the block
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks
looks like the following:
                            try
                            {
                               //Protected code
                            }catch(ExceptionType1 e1)
                            {
                               //Catch block
                            }catch(ExceptionType2 e2)
                            {
                               //Catch block
                            }catch(ExceptionType3 e3)
                            {
                               //Catch block
                            }



  The previous statements demonstrate three catch blocks, but you can have any
  number of them after a single try. If an exception occurs in the protected code, the
  exception is thrown to the first catch block in the list. If the data type of the exception
  thrown matches ExceptionType1, it gets caught there. If not, the exception passes
  down to the second catch statement. This continues until the exception either is
  caught or falls through all catches, in which case the current method stops execution
  and the exception is thrown down to the previous method on the call stack.
E   Here is code segment showing how to use multiple try/catch statements.


X
                 try
A                {
                    file = new FileInputStream(fileName);

M                   x = (byte) file.read();
                 }catch(IOException i)
                 {
P                   i.printStackTrace();
                    return -1;

L                }catch(FileNotFoundException f) //Not valid!
                 {
                    f.printStackTrace();
E                }
                    return -1;
If a method does not handle a checked exception, the method must
declare it using the throwskeyword. The throws keyword appears at the end of a
method's signature.
          You can throw an exception, either a newly instantiated one or an
exception that you just caught, by using the throw keyword. Try to understand the
different in throws and throw keywords.
          The following method declares that it throws a RemoteException:


       import java.io.*;
       public class className
       {
          public void deposit(double amount) throws RemoteException
          {
             // Method implementation
             throw new RemoteException();
          }
          //Remainder of class definition
       }
A method can declare that it throws more than one exception, in which case
the exceptions are declared in a list separated by commas. For example, the following
method      declares    that     it     throws    a   RemoteException      and     an
InsufficientFundsException:


        import java.io.*;
        public class className
        {
           public void withdraw(double amount) throws RemoteException,
                                      InsufficientFundsException
           {
               // Method implementation
           }
           //Remainder of class definition
        }
The finally keyword is used to create a block of code that follows a try block.
A finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you want to
execute, no matter what happens in the protected code. A finally block appears at the
end of the catch blocks and has the following syntax:

                     try
                     {
                        //Protected code
                     }catch(ExceptionType1 e1)
                     {
                        //Catch block
                     }catch(ExceptionType2 e2)
                     {
                        //Catch block
                     }catch(ExceptionType3 e3)
                     {
                        //Catch block
                     }finally
                     {
                        //The finally block always executes.
                     }
public class ExcepTest{
E           public static void main(String args[]){
               int a[] = new int[2];

X              try{
                  System.out.println("Access element three :" + a[3]);
               }catch(ArrayIndexOutOfBoundsException e){
A              }
                  System.out.println("Exception thrown :" + e);


M              finally{
                  a[0] = 6;
                  System.out.println("First element value: " +a[0]);
P              }
                  System.out.println("The finally statement is executed");


L        }
            }



E This would produce following result:
         Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
         First element value: 6
         The finally statement is executed
You can create your own exceptions in Java. Keep the following points in mind
when writing your own exception classes:
•       All exceptions must be a child of Throwable.
•       If you want to write a checked exception that is automatically enforced by the
Handle or Declare Rule, you need to extend the Exception class.
•       If you want to write a runtime exception, you need to extend the
RuntimeException class.
We can define our own Exception class as below:

                     class MyException extends Exception{
                     }


          You just need to extend the Exception class to create your own Exception
class. These are considered to be checked exceptions. The following
InsufficientFundsException class is a user-defined exception that extends the
Exception class, making it a checked exception. An exception class is like any other
class, containing useful fields and methods.
// File Name InsufficientFundsException.java
                  import java.io.*;
                  public class InsufficientFundsException extends
                  Exception
                  {
                     private double amount;
                     public InsufficientFundsException(double
                  amount)
                     {
                        this.amount = amount;
                     }
                     public double getAmount()
                     {
                        return amount;
                     }
                  }


   To demonstrate using our user-defined exception, the following CheckingAccount
   class contains a withdraw() method that throws an InsufficientFundsException.


Continuation
// File Name CheckingAccount.java   {
     import java.io.*;                    if(amount <= balance)
     public class CheckingAccount              { balance -= amount; }
     {                                         else
        private double balance;                {
        private int number;                       double needs = amount -
        public CheckingAccount(int       balance;
     number)                                      throw new
        {                                InsufficientFundsException(needs);
           this.number = number;               }
        }                                   }
        public void deposit(double          public double getBalance()
     amount)                                {
        {                                      return balance;
           balance += amount;               }
        }                                   public int getNumber()
        public void withdraw(double         {
     amount) throws                            return number;
                                            }
     InsufficientFundsException          }
Continuation
The following BankDemo program demonstrates invoking the deposit() and
  withdraw() methods of CheckingAccount.

  // File Name BankDemo.java
  public class BankDemo                             c.withdraw(100.00);
  {
     public static void main(String []     System.out.println("nWithdrawing
  args)                                    $600...");
     {                                              c.withdraw(600.00);
        CheckingAccount c = new
  CheckingAccount(101);                    }catch(InsufficientFundsException e)
        System.out.println("Depositing           {
  $500...");                                        System.out.println("Sorry,
        c.deposit(500.00);                 but you are short $"
        try                                                                  +
        {                                  e.getAmount());
                                                    e.printStackTrace();
  System.out.println("nWithdrawing              }
  $100...");                                   }
                                           }

Continuation
Compile all the above three files and run BankDemo, this would
     produce following result:



           Depositing $500...
           Withdrawing $100...
           Withdrawing $600...
           Sorry, but you are short $200.0
           InsufficientFundsException
                   at CheckingAccount.withdraw(CheckingAccount.java:25)
                   at BankDemo.main(BankDemo.java:13)




Continuation
A
AWTException
AclNotFoundException
ActivationException
AlreadyBoundException
ApplicationException
ArithmeticException
ArrayIndexOutOfBoundsException
AssertionException
                          B
BackingStoreException
BadAttributeValueExpException
BadLocationException
BadStringOperationException
B
BatchUpdateException
BrokenBarrierException
                           C
CertificateException
ChangedCharSetException
CharConversionException
CharacterCodingException
ClassNotFoundException
CloneNotSupportedException
ClosedChannelException
                           D
DataFormatException
DatatypeConfigurationException
D
DestroyFailedException
                           E
EOFException
ExecutionException
ExpandVetoException

                           F
FileLockInterruptionException
FileNotFoundException
FishFaceException
FontFormatException
                           G
GSSException
G
GeneralSecurityException

                              I
IIOException
IOException
IllegalAccessException
IllegalArgumentException
IllegalClassFormatException
IllegalStateException
IndexOutOfBoundsException
InputMismatchException
InstantiationException
InterruptedException
I
InterruptedIOException
IntrospectionException
InvalidApplicationException
InvalidMidiDataException
InvalidPreferencesFormatException
InvalidTargetObjectTypeException
InvocationTargetException
                              J
JAXBException
JMException

                              K
KeySelectorException
L
LastOwnerException
LineUnavailableException
                             M
MalformedURLException
MarshalException
MidiUnavailableException
MimeTypeParseException
                             N
NamingException
NegativeArraySizeException
NoSuchElementException
NoSuchFieldException
NoSuchMethodException
N
NoninvertibleTransformException
NotBoundException
NotOwnerException
NullPointerException
NumberFormatException
                            O
ObjectStreamException

                            P
ParseException
ParserConfigurationException
PrintException
PrinterException
PrivilegedActionException
P
PropertyVetoException
ProtocolException
                         R
RefreshFailedException
RemarshalException
RemoteException
RuntimeException
                         S
SAXException
SOAPException
SQLException
SQLWarning
SSLException
S
ScriptException
ServerNotActiveException
SocketException
SyncFailedException
                            T
TimeoutException
TooManyListenersException
TransformException
TransformerException
                            U
URIReferenceException
URISyntaxException
UTFDataFormatException
U
UnknownHostException
UnknownServiceException
UnmodifiableClassException
UnsupportedAudioFileException
UnsupportedCallbackException
UnsupportedEncodingException
UnsupportedFlavorException
UnsupportedLookAndFeelException
UnsupportedOperationException
UserException

                             X
XAException
X
XMLParseException
XMLSignatureException
XMLStreamException
XPathException
                        Z
ZipException
SAMPLE JAVA PROGRAM 1:


 import java.io.*;
 // A Java application to demonstrate making your own Exception class
 // This program catches the exception when the word "client" is
 // entered incorrectly.
 public class TestException
 {
           static String s = "";
           public static void main (String args[])
           {
               InputStreamReader is = new InputStreamReader(System.in);
               BufferedReader buf = new BufferedReader(is);

             System.out.println("Enter the word you cannot spell: ");

             try
{
                  s = buf.readLine();
        }
        catch (IOException e)
        {
                 System.out.println("IOException was " + e.getMessage());
        }

        try
        {
              checkSpelling(); // this method throws SpellException
         }
         catch (SpellException se) // but it is caught here
         {
              System.out.println("Spell exception was: " + se.getError());
         }
} // end main
SAMPLE JAVA PROGRAM 2:


  // Check spelling of typed in word. Throw exception if wrong.
  // Note how this method specifies that it throws such and such
  // exception. Does not have to be caught here.
     private static void checkSpelling() throws SpellException
     {
          if (s.equalsIgnoreCase("client"))
              System.out.println("OK");
          else
              throw new SpellException("Cannot spell client");
      }
  } // end main class

Contenu connexe

Tendances (19)

Oop suplemnertary september 2019
Oop suplemnertary september  2019Oop suplemnertary september  2019
Oop suplemnertary september 2019
 
java Applet Introduction
java Applet Introductionjava Applet Introduction
java Applet Introduction
 
Applet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java AppletsApplet Architecture - Introducing Java Applets
Applet Architecture - Introducing Java Applets
 
Exception handling
Exception handlingException handling
Exception handling
 
Java applet
Java appletJava applet
Java applet
 
Applet progming
Applet progmingApplet progming
Applet progming
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Creating your own exception
Creating your own exceptionCreating your own exception
Creating your own exception
 
Exceptional Handling in Java
Exceptional Handling in JavaExceptional Handling in Java
Exceptional Handling in Java
 
Exception handling
Exception handling Exception handling
Exception handling
 
Java applet - java
Java applet - javaJava applet - java
Java applet - java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java Applet
Java AppletJava Applet
Java Applet
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
27 applet programming
27  applet programming27  applet programming
27 applet programming
 

En vedette (20)

Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Event handling
Event handlingEvent handling
Event handling
 
Java Event Handling
Java Event HandlingJava Event Handling
Java Event Handling
 
Event handling
Event handlingEvent handling
Event handling
 
Event Handling in Java
Event Handling in JavaEvent Handling in Java
Event Handling in Java
 
tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Java awt
Java awtJava awt
Java awt
 
Awt
AwtAwt
Awt
 
Java session11
Java session11Java session11
Java session11
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
00 swing
00 swing00 swing
00 swing
 
Dacj 2-2 b
Dacj 2-2 bDacj 2-2 b
Dacj 2-2 b
 
Training on java niit (sahil gupta 9068557926)
Training on java niit (sahil gupta 9068557926)Training on java niit (sahil gupta 9068557926)
Training on java niit (sahil gupta 9068557926)
 
Event handling63
Event handling63Event handling63
Event handling63
 
c++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data typesc++ programming Unit 3 variables,data types
c++ programming Unit 3 variables,data types
 
C Programming basics
C Programming basicsC Programming basics
C Programming basics
 
Fundamentals of c programming
Fundamentals of c programmingFundamentals of c programming
Fundamentals of c programming
 
Input output streams
Input output streamsInput output streams
Input output streams
 
Java AWT
Java AWTJava AWT
Java AWT
 
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT IIC PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
 

Similaire à Event Handling Exceptions Guide

Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-ivRubaNagarajan
 
Unit5 java
Unit5 javaUnit5 java
Unit5 javamrecedu
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 

Similaire à Event Handling Exceptions Guide (20)

Java -Exception handlingunit-iv
Java -Exception handlingunit-ivJava -Exception handlingunit-iv
Java -Exception handlingunit-iv
 
Unit5 java
Unit5 javaUnit5 java
Unit5 java
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java Exceptions Handling
Java Exceptions Handling Java Exceptions Handling
Java Exceptions Handling
 
Java Exceptions
Java ExceptionsJava Exceptions
Java Exceptions
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Event handling
Event handlingEvent handling
Event handling
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 

Dernier

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 

Dernier (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 

Event Handling Exceptions Guide

  • 1. Event Handling and Exceptions
  • 2. The process of responding to an event. Window programs are said to be event-driven because they operate by performing actions in response to events.
  • 3. Contents The Delegation Event Model Event Classes Event Listeners Adapter Classes Inner Classes Anonymous Inner Classes
  • 4. The Delegation Event Model Applet is event-driven. Delegation Event model: JDK 1.1 introduced
  • 12. Exception in Java are classified on the basis of the exception handled by the java compiler.
  • 13. Contents: •Exception Handling in Java I. Introduction II. Common Exceptions III. “Catching” Exceptions IV. The Throwable Superclass V. Effectively using try-catch VI. Final thoughts of Exceptions •Type of Built-In Exceptions I. Checked Exception II. Unchecked Exception •Exception Hierarchy
  • 14. Contents: •Exceptions Methods •Catching Exceptions •Multiple Catch blocks •The throws/throw keywords •The Finally keywords •Declaring your own exception •Java Exceptions
  • 15. Exception Handling in Java I. Introduction An exception is an error thrown by a class or method reporting an error in operation. For example, dividing by zero is undefined in mathematics, and a calculation can fail if this winds up being the case because of an error in user input. In this particular case an ArithmeticException is thrown, and unless the programmer looks for this exception and manually puts in code to handle it, the program will crash stating the exception thrown and a stack trace, which would be unhelpful to a casual user of a Java program. If the programmer handles the exception, he could deliver a useful error to the user and return the user to the beginning of the program so that they could continue to use it.
  • 16. Exception Handling in Java II. Common Exceptions There are many different exceptions that can be thrown by a program, and the Java API contains quite a few. A lot are contained in the default package, java.lang; however, when you start using more functionality such as AWT, Swing, or java.io, the packages may also contain additional exceptions thrown by those libraries. As you start expanding the functionality, it might be a good idea to look at potential exceptions in the package and when they might be thrown in the course of your application.
  • 17. Exception Handling in Java II. Common Exceptions Here is a primer of some: ArithmeticException--thrown if a program attempts to perform division by zero ArrayIndexOutOfBoundsException--thrown if a program attempts to access an index of an array that does not exist StringIndexOutOfBoundsException--thrown if a program attempts to access a character at a non-existent index in a String NullPointerException--thrown if the JVM attempts to perform an operation on an Object that points to no data, or null Continuation:
  • 18. Exception Handling in Java II. Common Exceptions NumberFormatException--thrown if a program is attempting to convert a string to a numerical datatype, and the string contains inappropriate characters (i.e. 'z' or 'Q') ClassNotFoundException--thrown if a program can not find a class it depends at runtime (i.e., the class's ".class" file cannot be found or was removed from the CLASSPATH) IOException--actually contained in java.io, but it is thrown if the JVM failed to open an I/O stream As I said before, many different exceptions exist, and you should probably use your API documentation to learn about additional exceptions that may apply to your particular application. Continuation:
  • 19. Exception Handling in Java III. “Catching” Exceptions The java language contains keywords used specifically for testing for and handling exceptions. The ones we will be using here are try and catch, and they must be used in conjunction with one another. They sort of work like if-else: try{ /* Contains code to be tested */ }catch(Exception e){ /* Contains code to be executed if instanced of Exception is caught */}
  • 20. Exception Handling in Java III. “Catching” Exceptions The catch statement can look for all exceptions, using the Exception superclass, or it can catch a specific exception that you think could be thrown in the code you are testing with the tryblock. You can even have multiple catch blocks to catch and execute custom code for a number of different errors. A good thing to note would be that any particular exception that is caught is compared with each catch statement sequentially; so it is a good idea to put more generic exceptions, like Exception, towards the bottom of the list. Continuation:
  • 21. Exception Handling in Java IV. The Throwable Superclass The catch statement also stores an instance of the exception that was caught in the variable that the programmer uses, in the previous example Exception e. While all exceptions are subclasses of Exception, Exception itself is a subclass of Throwable, which contains a nice suite of methods that you can use to get all kinds of information to report about your exceptions: •getMessage()--returns the error message reported by the exception in a String •printStackTrace()--prints the stack trace of the exception to standard output, useful for debugging purposes in locating where the exception occurred
  • 22. Exception Handling in Java IV. The Throwable Superclass •printStackTrace(PrintStream s)--prints the stack trace to an alternative output stream •printStackTrace(PrintWriter s)--prints the stack trace to a file, this way you can log stack traces transparent to the user or log for later reference •toString()--if you just decide to print out the exception it will print out this: NAME_OF_EXCEPTION: getMessage(). Using the catch you now have control over what the error message is and where it goes. Continuation:
  • 23. Exception Handling in Java V. Effectively using try-catch In this section, I'm going to give you a few code samples on using try-catch blocks to give you an idea of the flexibility you as a programmer have over exceptions in your programs. The scenario is a user has input a file name to a program of a file that does not exist. In this scenario we are going to be using a text-based program; however, in a graphical environment you can easily use the catch block to draw dialog boxes. In the first example, we want to print a useful error message and exit the program gracefully, saving the user from the confusing stack trace with something useful:
  • 24. Exception Handling in Java V. Effectively using try-catch try{ BufferedReader in = new BufferedReader(new FileReader(userInput)); System.out.println(in.readLine()) }catch(IOException e){ System.err.println(e.getMessage()); System.err.println("Error: " + userInput + " is not a valid file. Please verify that the file exists and that you have access to it."); System.exit(1); } Continuation:
  • 25. Exception Handling in Java V. Effectively using try-catch Here, System.err.println() prints the error message to standard error output which is a high priority buffer that is used to report error messages to the console. If you're being a good programmer, you have separate methods that handle the different functionality of your programs; this way you can easily start the program from a previous place in the program before an exception occurs. In this next example, the user inputs the filename through the function getUserInput() elsewhere in the program; we want to report the "helpful error message" to the user and return the user to a place where he can enter a new filename. Continuation:
  • 26. Exception Handling in Java V. Effectively using try-catch try{ BufferedReader in = new BufferedReader(new FileReader(userInput)); return in.readLine(); }catch(IOException e){ System.err.println(e.getMessage()); System.err.println("Error: " + userInput + " is not a valid file. Please verify that the file exists and that you have access to it."); return getFileInput(getUserInput()); } Continuation:
  • 27. Exception Handling in Java V. Effectively using try-catch Now you have an idea of how you can control your programs once an exception is thrown, and this should give you the basic idea of how to work with exceptions in the Java language. Continuation:
  • 28. Exception Handling in Java VI. Final thoughts of Exceptions The best way to prevent your application from crashing from exceptions is to avoid exceptions in the first place. It is much more costly for a system to catch and handle exceptions than to account for potential errors directly in your code. A lot of times, an exception can point to a problem in the programmer's logic rather than in the user's use of the program. You should look for the cause of exceptions, and try to understand why it occurred and make sure that you really had considered everything. You will be making far more resilient and robust applications. Continuation:
  • 29. Types of Built In Exception I. Checked Exception These exception are the object of the Exception class or any of its subclasses except Runtime Exception class. These condition arises due to invalid input, problem with your network connectivity and problem in database.java.io.IOException is a checked exception. This exception is thrown when there is an error in input-output operation. In this case operation is normally terminated.
  • 30. Types of Built In Exception List of Checked Exceptions Exception Reason for Exception This Exception occurs when Java run-time system fail to find the ClassNotFoundException specified class mentioned in the program This Exception occurs when you create an object of an abstract Instantiation Exception class and interface This Exception occurs when you create an object of an abstract Illegal Access Exception class and interface This Exception occurs when the method you call does not exist in Not Such Method Exception class
  • 31. Types of Built In Exception II. Unchecked Exception These Exception arises during run-time ,that occur due to invalid argument passed to method. The java Compiler does not check the program error during compilation. For Example when you divide a number by zero, run- time exception is raised.
  • 32. Types of Built In Exception List of Unchecked Exceptions Exception Reason for Exception These Exception occurs, when you divide a number by zero Arithmetic Exception causes an Arithmetic Exception These Exception occurs, when you try to assign a reference Class Cast Exception variable of a class to an incompatible reference variable of another class These Exception occurs, when you assign an array which is not Array Store Exception compatible with the data type of that array These Exception occurs, when you assign an array which is not Array Index Out Of Bounds Exception compatible with the data type of that array These Exception occurs, when you try to implement an application Null Pointer Exception without referencing the object and allocating to a memory These Exception occurs, when you try to convert a string variable Number Format Exception in an incorrect format to integer (numeric format) that is not compatible with each other Negative ArraySizeException These are Exception, when you declare an array of negative size.
  • 33. An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: • A user has entered invalid data. • A file that needs to be opened cannot be found. • A network connection has been lost in the middle of communications, or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner.
  • 34. Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignored at the time of compilation. • Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. • Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
  • 35. All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors. The Exception class has two main subclasses : IOException class and RuntimeException Class.
  • 36. SN Methods with Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage() 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.
  • 37. A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block } A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.
  • 38. The following is an array is declared with 2 elements. Then the code tries E to access the 3rd element of the array which throws an exception. // File Name : ExcepTest.java X import java.io.*; public class ExcepTest{ A public static void main(String args[]){ try{ int a[] = new int[2]; M System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ P } System.out.println("Exception thrown :" + e); System.out.println("Out of the block"); L } } E This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block
  • 39. A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current method stops execution and the exception is thrown down to the previous method on the call stack.
  • 40. E Here is code segment showing how to use multiple try/catch statements. X try A { file = new FileInputStream(fileName); M x = (byte) file.read(); }catch(IOException i) { P i.printStackTrace(); return -1; L }catch(FileNotFoundException f) //Not valid! { f.printStackTrace(); E } return -1;
  • 41. If a method does not handle a checked exception, the method must declare it using the throwskeyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException: import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition }
  • 42. A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }
  • 43. The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. }
  • 44. public class ExcepTest{ E public static void main(String args[]){ int a[] = new int[2]; X try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ A } System.out.println("Exception thrown :" + e); M finally{ a[0] = 6; System.out.println("First element value: " +a[0]); P } System.out.println("The finally statement is executed"); L } } E This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed
  • 45. You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes: • All exceptions must be a child of Throwable. • If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. • If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods.
  • 46. // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. Continuation
  • 47. // File Name CheckingAccount.java { import java.io.*; if(amount <= balance) public class CheckingAccount { balance -= amount; } { else private double balance; { private int number; double needs = amount - public CheckingAccount(int balance; number) throw new { InsufficientFundsException(needs); this.number = number; } } } public void deposit(double public double getBalance() amount) { { return balance; balance += amount; } } public int getNumber() public void withdraw(double { amount) throws return number; } InsufficientFundsException } Continuation
  • 48. The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount. // File Name BankDemo.java public class BankDemo c.withdraw(100.00); { public static void main(String [] System.out.println("nWithdrawing args) $600..."); { c.withdraw(600.00); CheckingAccount c = new CheckingAccount(101); }catch(InsufficientFundsException e) System.out.println("Depositing { $500..."); System.out.println("Sorry, c.deposit(500.00); but you are short $" try + { e.getAmount()); e.printStackTrace(); System.out.println("nWithdrawing } $100..."); } } Continuation
  • 49. Compile all the above three files and run BankDemo, this would produce following result: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) Continuation
  • 51. B BatchUpdateException BrokenBarrierException C CertificateException ChangedCharSetException CharConversionException CharacterCodingException ClassNotFoundException CloneNotSupportedException ClosedChannelException D DataFormatException DatatypeConfigurationException
  • 52. D DestroyFailedException E EOFException ExecutionException ExpandVetoException F FileLockInterruptionException FileNotFoundException FishFaceException FontFormatException G GSSException
  • 53. G GeneralSecurityException I IIOException IOException IllegalAccessException IllegalArgumentException IllegalClassFormatException IllegalStateException IndexOutOfBoundsException InputMismatchException InstantiationException InterruptedException
  • 55. L LastOwnerException LineUnavailableException M MalformedURLException MarshalException MidiUnavailableException MimeTypeParseException N NamingException NegativeArraySizeException NoSuchElementException NoSuchFieldException NoSuchMethodException
  • 56. N NoninvertibleTransformException NotBoundException NotOwnerException NullPointerException NumberFormatException O ObjectStreamException P ParseException ParserConfigurationException PrintException PrinterException PrivilegedActionException
  • 57. P PropertyVetoException ProtocolException R RefreshFailedException RemarshalException RemoteException RuntimeException S SAXException SOAPException SQLException SQLWarning SSLException
  • 58. S ScriptException ServerNotActiveException SocketException SyncFailedException T TimeoutException TooManyListenersException TransformException TransformerException U URIReferenceException URISyntaxException UTFDataFormatException
  • 61. SAMPLE JAVA PROGRAM 1: import java.io.*; // A Java application to demonstrate making your own Exception class // This program catches the exception when the word "client" is // entered incorrectly. public class TestException { static String s = ""; public static void main (String args[]) { InputStreamReader is = new InputStreamReader(System.in); BufferedReader buf = new BufferedReader(is); System.out.println("Enter the word you cannot spell: "); try
  • 62. { s = buf.readLine(); } catch (IOException e) { System.out.println("IOException was " + e.getMessage()); } try { checkSpelling(); // this method throws SpellException } catch (SpellException se) // but it is caught here { System.out.println("Spell exception was: " + se.getError()); } } // end main
  • 63. SAMPLE JAVA PROGRAM 2: // Check spelling of typed in word. Throw exception if wrong. // Note how this method specifies that it throws such and such // exception. Does not have to be caught here. private static void checkSpelling() throws SpellException { if (s.equalsIgnoreCase("client")) System.out.println("OK"); else throw new SpellException("Cannot spell client"); } } // end main class