Java programming-Event Handling

6,765 views

Published on

Published in: Technology, News & Politics
1 Comment
5 Likes
Statistics
Notes
  • these slides are really helpful
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total views
6,765
On SlideShare
0
From Embeds
0
Number of Embeds
338
Actions
Shares
0
Downloads
246
Comments
1
Likes
5
Embeds 0
No embeds

No notes for slide

Java programming-Event Handling

  1. 1. Event Handling and Exceptions
  2. 2. The process of responding to anevent. Window programs aresaid to be event-driven becausethey operate by performingactions in response to events.
  3. 3. Contents The Delegation Event Model Event Classes Event Listeners Adapter Classes Inner Classes Anonymous Inner Classes
  4. 4. The Delegation Event ModelApplet is event-driven.Delegation Event model: JDK 1.1 introduced
  5. 5. Event Classes
  6. 6. Event Classes
  7. 7. Event Listeners
  8. 8. Adapter Classes
  9. 9. Delegated Event Model
  10. 10. Inner Classes
  11. 11. Anonymous Inner Classes
  12. 12. Exception in Java are classifiedon the basis of the exceptionhandled by the java compiler.
  13. 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. 14. Contents:•Exceptions Methods•Catching Exceptions•Multiple Catch blocks•The throws/throw keywords•The Finally keywords•Declaring your own exception•Java Exceptions
  15. 15. Exception Handling in JavaI. 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. 16. Exception Handling in JavaII. 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. 17. Exception Handling in JavaII. 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. 18. Exception Handling in JavaII. 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 classs ".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. 19. Exception Handling in JavaIII. “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. 20. Exception Handling in JavaIII. “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. 21. Exception Handling in JavaIV. 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. 22. Exception Handling in JavaIV. 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. 23. Exception Handling in JavaV. Effectively using try-catch In this section, Im 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. 24. Exception Handling in JavaV. 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. 25. Exception Handling in JavaV. 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 youre 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. 26. Exception Handling in JavaV. 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. 27. Exception Handling in JavaV. 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. 28. Exception Handling in JavaVI. 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 programmers logic rather than in the users 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. 29. Types of Built In ExceptionI. Checked ExceptionThese exception are the object of the Exception class orany of its subclasses except Runtime Exception class.These condition arises due to invalid input, problemwith your network connectivity and problem indatabase.java.io.IOException is a checked exception.This exception is thrown when there is an error ininput-output operation. In this case operation isnormally terminated.
  30. 30. Types of Built In ExceptionList of Checked Exceptions Exception Reason for Exception This Exception occurs when Java run-time system fail to find theClassNotFoundException specified class mentioned in the program This Exception occurs when you create an object of an abstractInstantiation Exception class and interface This Exception occurs when you create an object of an abstractIllegal Access Exception class and interface This Exception occurs when the method you call does not exist inNot Such Method Exception class
  31. 31. Types of Built In ExceptionII. Unchecked ExceptionThese Exception arises during run-time ,that occur dueto invalid argument passed to method. The javaCompiler does not check the program error duringcompilation.For Example when you divide a number by zero, run-time exception is raised.
  32. 32. Types of Built In Exception List of Unchecked Exceptions Exception Reason for Exception These Exception occurs, when you divide a number by zeroArithmetic Exception causes an Arithmetic Exception These Exception occurs, when you try to assign a referenceClass Cast Exception variable of a class to an incompatible reference variable of another class These Exception occurs, when you assign an array which is notArray Store Exception compatible with the data type of that array These Exception occurs, when you assign an array which is notArray Index Out Of Bounds Exception compatible with the data type of that array These Exception occurs, when you try to implement an applicationNull Pointer Exception without referencing the object and allocating to a memory These Exception occurs, when you try to convert a string variableNumber Format Exception in an incorrect format to integer (numeric format) that is not compatible with each otherNegative ArraySizeException These are Exception, when you declare an array of negative size.
  33. 33. An exception is a problem that arises during the execution of a program. Anexception 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 programmererror, and others by physical resources that have failed in some manner.
  34. 34. • Checked exceptions: A checked exception is an exception that istypically a user error or a problem that cannot be foreseen by theprogrammer. For example, if a file is to be opened, but the file cannot befound, an exception occurs. These exceptions cannot simply be ignoredat the time of compilation.• Runtime exceptions: A runtime exception is an exception thatoccurs that probably could have been avoided by the programmer. Asopposed to checked exceptions, runtime exceptions are ignored at thetime of compliation.• Errors: These are not exceptions at all, but problems that arisebeyond the control of the user or the programmer. Errors are typicallyignored 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 alsoignored at the time of compilation.
  35. 35. All exception classes are subtypes of the java.lang.Exception class. The exceptionclass is a subclass of the Throwable class. Other than the exception class there isanother subclass called Error which is derived from the Throwable class.Errors are not normally trapped form the Java programs. These conditionsnormally happen in case of severe failures, which are not handled by the javaprograms. Errors are generated to indicate errors generated by the runtimeenvironment. Example : JVM is out of Memory. Normally programs cannotrecover from errors.The Exception class has two main subclasses : IOException class andRuntimeException Class.
  36. 36. SN Methods with Description1 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. 37. A method catches an exception using a combination ofthe try and catch keywords. A try/catch block is placed around the code thatmight generate an exception. Code within a try/catch block is referred to asprotected 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 tocatch. If an exception occurs in protected code, the catch block (or blocks) thatfollows the try is checked. If the type of exception that occurred is listed in acatch block, the exception is passed to the catch block much as an argument ispassed into a method parameter.
  38. 38. The following is an array is declared with 2 elements. Then the code triesE to access the 3rd element of the array which throws an exception. // File Name : ExcepTest.javaX 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. 39. A try block can be followed by multiple catch blocks. The syntax for multiple catch blockslooks 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. 40. E Here is code segment showing how to use multiple try/catch statements.X tryA { 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. 41. If a method does not handle a checked exception, the method mustdeclare it using the throwskeyword. The throws keyword appears at the end of amethods signature. You can throw an exception, either a newly instantiated one or anexception that you just caught, by using the throw keyword. Try to understand thedifferent 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. 42. A method can declare that it throws more than one exception, in which casethe exceptions are declared in a list separated by commas. For example, the followingmethod declares that it throws a RemoteException and anInsufficientFundsException: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition }
  43. 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 toexecute, no matter what happens in the protected code. A finally block appears at theend 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. 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. 45. You can create your own exceptions in Java. Keep the following points in mindwhen 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 theHandle or Declare Rule, you need to extend the Exception class.• If you want to write a runtime exception, you need to extend theRuntimeException 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 Exceptionclass. These are considered to be checked exceptions. The followingInsufficientFundsException class is a user-defined exception that extends theException class, making it a checked exception. An exception class is like any otherclass, containing useful fields and methods.
  46. 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. 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. 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. 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
  50. 50. AAWTExceptionAclNotFoundExceptionActivationExceptionAlreadyBoundExceptionApplicationExceptionArithmeticExceptionArrayIndexOutOfBoundsExceptionAssertionException BBackingStoreExceptionBadAttributeValueExpExceptionBadLocationExceptionBadStringOperationException
  51. 51. BBatchUpdateExceptionBrokenBarrierException CCertificateExceptionChangedCharSetExceptionCharConversionExceptionCharacterCodingExceptionClassNotFoundExceptionCloneNotSupportedExceptionClosedChannelException DDataFormatExceptionDatatypeConfigurationException
  52. 52. DDestroyFailedException EEOFExceptionExecutionExceptionExpandVetoException FFileLockInterruptionExceptionFileNotFoundExceptionFishFaceExceptionFontFormatException GGSSException
  53. 53. GGeneralSecurityException IIIOExceptionIOExceptionIllegalAccessExceptionIllegalArgumentExceptionIllegalClassFormatExceptionIllegalStateExceptionIndexOutOfBoundsExceptionInputMismatchExceptionInstantiationExceptionInterruptedException
  54. 54. IInterruptedIOExceptionIntrospectionExceptionInvalidApplicationExceptionInvalidMidiDataExceptionInvalidPreferencesFormatExceptionInvalidTargetObjectTypeExceptionInvocationTargetException JJAXBExceptionJMException KKeySelectorException
  55. 55. LLastOwnerExceptionLineUnavailableException MMalformedURLExceptionMarshalExceptionMidiUnavailableExceptionMimeTypeParseException NNamingExceptionNegativeArraySizeExceptionNoSuchElementExceptionNoSuchFieldExceptionNoSuchMethodException
  56. 56. NNoninvertibleTransformExceptionNotBoundExceptionNotOwnerExceptionNullPointerExceptionNumberFormatException OObjectStreamException PParseExceptionParserConfigurationExceptionPrintExceptionPrinterExceptionPrivilegedActionException
  57. 57. PPropertyVetoExceptionProtocolException RRefreshFailedExceptionRemarshalExceptionRemoteExceptionRuntimeException SSAXExceptionSOAPExceptionSQLExceptionSQLWarningSSLException
  58. 58. SScriptExceptionServerNotActiveExceptionSocketExceptionSyncFailedException TTimeoutExceptionTooManyListenersExceptionTransformExceptionTransformerException UURIReferenceExceptionURISyntaxExceptionUTFDataFormatException
  59. 59. UUnknownHostExceptionUnknownServiceExceptionUnmodifiableClassExceptionUnsupportedAudioFileExceptionUnsupportedCallbackExceptionUnsupportedEncodingExceptionUnsupportedFlavorExceptionUnsupportedLookAndFeelExceptionUnsupportedOperationExceptionUserException XXAException
  60. 60. XXMLParseExceptionXMLSignatureExceptionXMLStreamExceptionXPathException ZZipException
  61. 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. 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. 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

×