1 / 28

Java Exception handling

Java Exception handling

Download Presentation

Java Exception handling

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. Exception Handling

  2. Error Can not be handled by Programmer Example Not enough space LOW Memory NO OS Support Lack of h/w Support Stack Overflow

  3. Exception An exception is an abnormal event that arises during the execution of the program and disrupts the normal flow of the program.

  4. “Handling” “what happens after an abnormality occurred?“ Is actually important. If these exceptions are not handled properly, the program terminates abruptly and may cause severe consequences. For example, the network connections, database connections and files may remain opened; database and file records may be left in an inconsistent state.

  5. “Handling” Suppose there are 10 statements in your program and there occurs an exception at statement 5, the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform exception handling, the rest of the statement will be executed. That is why we use exception handling in Java.

  6. Checked Exception Checked exception is an exception due to an error situation that can be foreseen by the programmer A checked exception must be handled by the using try-catch block or at least by using throws clause with that method. Non Compliance of this rule result in a compile time error. For example: FileNotFoundException, SQLException

  7. Unchecked Exception • Class RuntimeException and all its subclasses are unchecked exception. • An unchecked exception is an exception which could have been avoided by the programmer. • If there is a chance of unchecked exception than it is ignored by the compiler. For example NumberFormatException, NullPointerException,IndexOutOfBoundsException etc.

  8. “try-catch” block • Any part of the code that can generate exception should be kept inside try block, and exception should be handled in the catch block. • The corrective action in case of an exception should be kept in the catch block. • However, a single block of code can raise more than one exception • We can specify two or more catch clauses followed by try block • Catch clauses are executed in order occurrence. If one is executed(After match) others are bypassed and the execution after try catch blocks starts.

  9. “try-catch” block • In case of using multiple catch clauses, the sub class Exception must come before super class. • This is done because if super class Exception comes first than catch block having sub class will be unreachable. This will apparently manifest unreachable code error.

  10. public void testTryCatch() { FileInputStreamfis; try { fis=new FileInputStream("writehere.txt"); intch=0; int count=1; try { while((ch=fis.read())!=-1) { System.out.print((char)ch); if(ch==' ') { count++; } } System.out.println("\n No of words in file:"+count); fis.close(); } catch (IOException e) { System.out.println("IO Exception occured"); } } catch (FileNotFoundException e) { System.out.println("File not found"); } }

  11. Nested “try-catch” block • Try statement can be nested. • If inner try bock doesn't have a catch block than catch block of outer try block will handle the exception • This continues until one catch block doesn’t handle the Exception or till all the try blocks are exhausted • If no catch matches than java runtime handles the exception

  12. package com.io.test; import java.io.FileNotFoundException; public class FinallyDemo { public static void main(String arg[]) { System.out.println("Welcome"); try { System.out.println("inside try before exception"); try { System.out.println("nested"); } catch (ArithmeticException e) { System.out.println("Subclass Exception"); } } catch (Exception e) { System.out.println("Super class Exception"); } } }

  13. “throws” • Sometimes a method may cause an exception but does not seek to handle it. • This method must specify this behaviour so that callers of this methods may protect themselves against that Exception. • While declaring such method programmer have to specify which exception this method may throw using “throws” keyword. • Multiple Exceptions may be added using comma separated list

  14. public class ThrowsDemo { public void testThrows() throws IOException { FileOutputStreamfos=new FileOutputStream("writehere.txt"); String str="welcome to exception handling"; byte[] b=str.getBytes(); fos.write(b); System.out.println("Written to file successfully"); fos.close(); } } Exception is bypassed public static void main(String[] arg) { ThrowsDemo td=new ThrowsDemo(); try { td.testThrows(); } catch (IOException e) { System.out.println("Could not write to the file"); } }

  15. Rule of Throws(Overriding method) • The overriding method must NOT throw checked Exceptions those are new or broader than those declared by the overridden method. • For example: A method a method throwing SQLException can not be overridden by a method throwing IOException or ANY other Exception unless the Exception is subclass of SQLException class. • Or A method declared in Super class A throwing Exception X , if overridden in Sub class B can only throw either X as Exception or Any Exception Sub class of X. • This rule is applicable only for checked Exceptions

  16. public class A { public void test() throws FileNotFoundException { FileInputStreamfis=new FileInputStream("ok.txt"); } } public class B extends A{ public void test() throws IOException { FileInputStreamfis=new FileInputStream("ok.txt"); } } Compilation Error Broader Class Exception

  17. “Throw” • System generated Exceptions are thrown Automatically. However, sometimes you may also yield to throw Exception explicitly. This can be done using “throw” keyword. • Syntax: throw ThrowableInstance Here ThrowableInstance must be object of Throwable or its subclass

  18. public class ThrowDemo { public void test() { System.out.println("in Test Method"); throw new ArithmeticException(); } } Output Output: in Test Method Exception in thread "main" java.lang.ArithmeticException at com.io.test.ThrowDemo.test(ThrowDemo.java:8) at com.io.test.DemoThrow.main(DemoThrow.java:7) public class DemoThrow { public static void main(String[] args) { ThrowDemo td=new ThrowDemo(); td.test(); System.out.println("main method"); } }

  19. public class DemoThrow { public static void main(String[] args) { Scanner scan=new Scanner(System.in); System.out.println("Enter a number"); int k=scan.nextInt(); if(k<0) { throw new ArithmeticException(); }else if(k>=0) { throw new ArrayIndexOutOfBoundsException(); }else { System.out.println("your number is correct:"+k); } } } Other Example

  20. “User defined Exceptions” • Apart from rich set of built-in Exceptions, JAVA provide the ability to user to define Their Own Exception classes. • For example: if we want minimum amount to be filled before starting a bank credit or debit transaction. • All user defined Exceptions must be subclasses of Exception class or its sub classes. • To display meaningful information, user need to override the toString() method.

  21. public class UserDefinedExcepton extends Exception { @Override public String toString() { return "Wrong Amount Entered"; } } public class UserDemo { public static void main(String arg[]) throws UserDefinedExcepton { System.out.println("Enter amoung to withdraw"); Scanner scan=new Scanner(System.in); int k=scan.nextInt(); if(k<100) { throw new UserDefinedExcepton(); } else { System.out.println("Your account is debited Rs "+k); } } }

  22. Output Enter amoung to withdraw 12 Exception in thread "main" Wrong Amount Entered at com.io.test.UserDemo.main(UserDemo.java:14)

  23. “finally” An exception can force a program to follow a non linear path and it can bypass few statements. For example a connection with database is opened and then some exception occurs. The program will terminate eventually, and connection will still remain open. Finally block can be used to close the connection. Finally block guarantees that the statement will be executed in all circumstances

  24. public class FinallyDemo { public static void main(String arg[]) throws FileNotFoundException { System.out.println("Welcome"); try { System.out.println("inside try before exception"); throw new FileNotFoundException(); } finally { System.out.println("inside finally"); } } } Welcome inside try before exception Exception in thread "main" inside finally java.io.FileNotFoundException at com.io.test.FinallyDemo.main(FinallyDemo.java:10)

  25. public class FinallyDemo { public static void main(String arg[]) { System.out.println("Welcome"); try { System.out.println("inside try before exception"); throw new FileNotFoundException(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { System.out.println("inside finally"); } } }

  26. Output Welcome inside try before exception java.io.FileNotFoundException at com.io.test.FinallyDemo.main(FinallyDemo.java:11) inside finally

More Related