1 / 153

Dr. D. Y. Patil Institute of Engineering, Management and Research, Akurdi , Pune - 44

Dr. D. Y. Patil Institute of Engineering, Management and Research, Akurdi , Pune - 44 Department of Electronics and Telecommunication Engineering Unit VI Multithreading, Exception handling & Applets Prepared By:- Mrs. Neha Tiwari.

sharonr
Download Presentation

Dr. D. Y. Patil Institute of Engineering, Management and Research, Akurdi , Pune - 44

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Dr. D. Y. Patil Institute of Engineering, Management and Research, Akurdi, Pune - 44 Department of Electronics and Telecommunication Engineering Unit VI Multithreading, Exception handling & Applets Prepared By:- Mrs. Neha Tiwari

  2. Introduction to multithreading: Introduction, Creating thread and extending thread class. Concept of Exception handling: Introduction, Types of errors, Exception handling syntax, Multiple catch statements. I/O basics, Reading console inputs, Writing Console output.

  3. Applets: Concepts of Applets, differences between applets and applications, life cycle of an applet, types of applets, creating a simple applet.

  4. UNIT –VI –Chapter No-01-Exception-Handling • Exception-Handling Fundamentals • A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code . • When an exceptional condition arises, an object representing that exception is created and thrown in the method that caused the error. • Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. • Program statements that you want to monitor for exceptions are contained within a try block. • To manually throw an exception, use the keyword throw. • Any exception that is thrown out of a method must be specified as such by a throws clause. • Any code that absolutely must be executed after a try block completes is put in a finally block. • System-generated exceptions are automatically thrown by the Java runtime system.

  5. This is the general form of an exception-handling block: try { // block of code to monitor for errors } catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } // ... finally { // block of code to be executed after try block ends } Here, ExceptionTypeis the type of exception that has occurred.

  6. The exception handling in java is one of the powerful mechanism to handle the runtime errors so that normal flow of the application can be maintained. • Exceptions are nothing but the runtime errors. • It generally alters the flow of program execution. • When exception occurs,program execution stops and terminates the program abnormally. • Program execution does not continue.In this situation we get system generated error on screen.

  7. The statement after the instructions which causes exceptions does not get executed. • It is not always acceptable to terminate program abnormally. • In safety critical applications it not acceptable to terminate program abnormally.Exceptions occur due to so many reasons. • Some of the reasons are as follows: • 1] Invalid Input • 2] File not available • 3] Network Error • 4] In sufficient memory • 5] Improper use of array

  8. Some of the real time exceptions are 1] We are trying to divide the number by zero 2] We are trying to open file which is not existing 3] We are storing incompatible value in array 4] RAM is not enough to load your program. 5] WE are trying to access address which is pointing to NULL. 6] Improper type conversion. NOTE: When exception occurs , statements following that instructions will not get executed.

  9. Example: public class Exception { public static void main(String args[]) { System.out.println(“This is exception Example”); int a=100; double div=a/0; System.out.println(“Division of number is:”+div); System.out.println(“This statement is after printing result”); } } Output: This is exception Example Exception in thread “main” java.lang.ArithmeticException:/by zero

  10. Exception is an abnormal condition. • In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime. • Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc.

  11. Advantage of Exception Handling The core advantage of exception handling is to maintain the normal flow of the application. Exception normally disrupts the normal flow of the application that is why we use exception handling. 

  12. statement 1;   statement 2;   statement 3;   statement 4;   statement 5;//exception occurs   statement 6;   statement 7;   statement 8;   statement 9;   statement 10;   Suppose there is 10 statements in your program and there occurs an exception at statement 5, rest of the code will not be executed i.e. statement 6 to 10 will not run. If we perform exception handling, rest of the statement will be executed. That is why we use exception handling in java.

  13. Type of Error Java.lang Fig: Exception Hierarchy Object Throwable Errors Exceptions Runtime exceptions Other exceptions

  14. Java provides mechanism to handle exceptional conditions. • It is possible with concept of exception handling • Exception handling is fundamental in java programming language. • It is one of the reasons why java is so successful. • All exception in java is subclass of java.lang.Object. • Exception class is subclass of Throwable. • Throwable have two subclasses one is exception and another is errors. • Errors are mostly beyond the reach of programmer because programmers cannot deal with hardware problem. • Error handling is not part of exception handling mechanism. • Exception again have two subclasses namely runtime exceptions and other exceptions.

  15. Types of Exceptions There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun microsystem says there are three types of exceptions: 1. Checked Exception 2. Unchecked Exception 3. Error

  16. Difference between checked and unchecked exceptions 1) Checked Exception The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions.These exceptions should not be ignored and must be corrected by the programmer. e.g.IOException, SQLException etc. Checked exceptions are checked at compile-time.

  17. ExceptionError.java import java.io.File; import java.io.FileReader; public class ExceptionError{ public static void main(String args[]) { File file=new File(“E://file.txt”); FileReaderfr=new FileReader(file); } }

  18. Output: Exception in thread “main” java.lang.Error: Unresolved compilation problem: Unhandled exception type FileNotFoundException at a.ExceptionError.main(ExceptionError.java)

  19. 2) Unchecked Exception The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime. 3) Error Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.

  20. Example: package a; public class UncheckedException{ public static void main(String args[]) { System.out.println(“Example of unchecked exceptions”); int a=10; double div=a/0; System.out.println(“Division”+div); } } Output: Example of unchecked exceptions Exception in thread “main” java.lang.ArithmeticException: / by zero at a.UncheckedException.main(UncheckedException.java)

  21. Exception Types • All exception types are subclasses of the built-in class Throwable. • Immediately below Throwableare two subclasses that partition exceptions into two distinct branches. • One branch is headed by Exception.This class is used for exceptional conditions that user programs should catch. This is also the • class that you will subclass to create your own custom exception types. There is an important subclass of Exception, called RuntimeException. • Exceptions of this type are automatically defined for the programs that you write and include things such as division by zero and invalid array indexing. • The other branch is topped by Error. which defines exceptions that are not expected to be caught under normal circumstances by your program. Exceptions of type Error are used by the Java run-time system to indicate errors having to do with the run-time environment, itself. Stack overflow is an example of such an error.

  22. Exception handling syntax Java Exception Handling Keywords There are 5 keywords used in java exception handling. 1. try 2. catch 3. finally 4. throw 5. throws

  23. To handle the exceptions we need to identify the section of code which may result into runtime error and apply the exception handling mechanisms. • It is always good programming practice to handle the exceptions.

  24. Common scenarios where exceptions may occur There are given some scenarios where unchecked exceptions can occur. They are as follows: 1) Scenario where ArithmeticException occurs If we divide any number by zero, there occurs an ArithmeticException. int a=50/0;//ArithmeticException 2) Scenario where NullPointerException occurs If we have null value in any variable, performing any operation by the variable occurs an NullPointerException. String s=null;   System.out.println(s.length());//NullPointerException 3) Scenario where NumberFormatException occurs The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException. String s="abc";   inti=Integer.parseInt(s);//NumberFormatException

  25. String s="abc";   inti=Integer.parseInt(s);//NumberFormatException 4) Scenario where ArrayIndexOutOfBoundsException occurs If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below: int a[]=newint[5];   a[10]=50; //ArrayIndexOutOfBoundsException

  26. Java try-catch • Java try block • Java try block is used to enclose the code that might throw an exception. • It must be used within the method. • Java try block must be followed by either catch or finally block.

  27. 1. Syntax of java try-catch try{   //code that may throw exception   }catch(Exception_class_Name ref){}   2. Syntax of try-finally block try{   //code that may throw exception   }finally{} 

  28. Java catch block • Java catch block is used to handle the Exception. • It must be used after the try block only. • You can use multiple catch block with a single try. • Problem without exception handling • publicclass Testtrycatch1{   • publicstaticvoid main(String args[]){   • int data=50/0; //may throw exception   • System.out.println("rest of the code...");   • }   • }  

  29. Output: Compile by: javac Testtrycatch1.java Run by: java Testtrycatch1 Exception in thread "main" java.lang.ArithmeticException: / by zeroat Testtrycatch1.main(Testtrycatch1.java:3) As displayed in the above example, rest of the code is not executed (in such case, rest of the code... statement is not printed). There can be 100 lines of code after exception. So all the code after exception will not be executed.

  30. Solution by exception handling Let's see the solution of above problem by java try-catch block. publicclass Testtrycatch2{   publicstaticvoid main(String args[]){   try{   int data=50/0;      }catch(ArithmeticException e){System.out.println(e);}   System.out.println("rest of the code...");   }  }

  31. Compile by: javac Testtrycatch2.java Run by: java Testtrycatch2 java.lang.ArithmeticException: / by zerorest of the code... Now, as displayed in the above example, rest of the code is executed i.e. rest of the code... statement is printed.

  32. Internal working of java try-catch block

  33. The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks: 1. Prints out exception description. 2.Prints the stack trace (Hierarchy of methods where the exception occurred). 3. Causes the program to terminate. But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.

  34. Example: TryCatch.java public class TryCatch{ public static void main(String args[]){ System.out.println(“Try Catch example”); int a=10; double div; System.out.println(“Before try catch”); try{ div=a/0; System.out.println(“Division is:”+div); }catch(ArithmeticException e){ System.out.println(“Divide by zero error”); } System.out.println(“After run time error”);}}

  35. Output: Try Catch example Before try catch Divide by zero error After run time error 1.Try block executed normally if there is no run time error. 2.If run time error occurs then it will directly jump to catch block and execute the statement from it. 3.Once catch block is over it will execute remaining statement after catch block. 4. After catch it will not go back to try block to execute remaining statements.

  36. Example: TryCatchDesc.java public class TryCatchDesc{ public static void main(String args[]){ System.out.println(“Try Catch example with exception description”); int a=10; double div; System.out.println(“Before try catch”); try{ div=a/0; System.out.println(“Division is:”+div); }catch(ArithmeticException e){ System.out.println(“Exception description”+e); } System.out.println(“After run time error”); } }

  37. Output: Try Catch example with exception description Before try catch Divide by zero error Exception description java.lang.ArithmeticException: / by zero After run time error

  38. Uncaught Exceptions class Exc0 { public static void main(String args[]) { int d = 0; int a = 42 / d; } } • When the Java run-time system detects the attempt to divide by zero, it constructs a new exception object and then throws this exception. This causes the execution of Exc0 to stop, because once an exception has been thrown, it must be caught by an exception handler and dealt with immediately. • In this example, we haven’t supplied any exception handlers of our own, so the exception is caught by the default handler provided by the Java run-time • system. Any exception that is not caught by your program will ultimately be processed by the default handler. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program.

  39. Here is the exception generated when this example is executed: java.lang.ArithmeticException: / by zero at Exc0.main(Exc0.java:4) Using try and catch class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } This program generates the following output: Division by zero. After catch statement.

  40. Java catch multiple exceptions • If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch block. • Simple example of java multi-catch block.

  41. publicclassTestMultipleCatchBlock{   publicstaticvoid main(String args[]){   try{   int a[]=newint[5];       a[5]=30/0;      }   catch(ArithmeticException e) { System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed");}   catch(Exception e) { System.out.println("common task completed"); } System.out.println("rest of the code...");  }}

  42. Compile by: javac TestMultipleCatchBlock.java Run by: java TestMultipleCatchBlock task1 is completedrest of the code... NOTE: Rule 1: At a time only one Exception is occured and at a time only one catch block is executed. Rule2: All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticExceptionmust come before catch for Exception .

  43. class TestMultipleCatchBlock1{   publicstaticvoid main(String args[]){   try{   int a[]=newint[5];       a[5]=30/0;      }   catch(Exception e) { System.out.println("common task completed");}   catch(ArithmeticException e) { System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("task 2 completed");}   System.out.println("rest of the code...");  }}

  44. Compile by: javac TestMultipleCatchBlock1.java eCatchBlock1.java:8: error: exception ArithmeticException has already been caughtpleted");}^eCatchBlock1.java:9: error: exception ArrayIndexOutOfBoundsException has already been caughtask 2 completed");}^2 errors

  45. Multiple catch Clauses • In some cases, more than one exception could be raised by a single piece of code. • To handle this type of situation, you can specify two or more catch clauses, each catching a different type of exception. • When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. • After one catch statement executes, the others are bypassed, and execution continues after the try / catch block. // Demonstrate multiple catch statements. class MultipleCatches { public static void main(String args[]) { try { int a = args.length; System.out.println("a = " + a); int b = 42 / a; int c[] = { 1 }; c[42] = 99; } catch(ArithmeticException e) { System.out.println("Divide by 0: " + e); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("Array index oob: " + e); } System.out.println("After try/catch blocks."); } }

  46. Nested try Statements • The try statement can be nested. That is, a try statement can be inside the block of another try. Each time a try statement is entered, the context of that exception is pushed on the stack. • If an inner try statement does not have a catch handler for a particular exception, the stack is unwound and the next try statement’s catch handlers are inspected for a match. • This continues until one of the catch statements succeeds, or until all of the nested try statements are exhausted. If no catch statement matches, then the Java run-time system will handle the exception

  47. Java Nested try block The try block within a try block is known as nested try block in java. Why use nested try block Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

  48. Syntax: ....   try {       statement 1;       statement 2;   try     {           statement 1;           statement 2;       }   catch(Exception e)       {       }   }   catch(Exception e)   {   }   ....  

  49. Java nested try example class Excep6{   publicstaticvoid main(String args[]){   try{   try{   System.out.println("going to divide");   int b =39/0;       }catch(ArithmeticException e){System.out.println(e);}  

More Related