Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

The satisfaction and euphoria that accompany the successfu...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Exception Handling

Errors:
It is a runtime error which wi...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

ArrayIndexOutOfBoundsException
int a[]=new int[10];
System...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Flow of Control of Exceptions
Class A{
Class method3()
voi...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Hierarchy of Exception classes

Exception Handling in Java...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

catch block
 Catch block is used to handle the Exception....
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

}
No statements allowed here as no
statements are allowed ...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Nested try block: try block within a try block is known as...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Note: Before terminating the program, JVM executes finally...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

OutPut:
finally block is always executed
Exception in thre...
Exception Handling in Java

For age greater than 18
class Excep13{
void validate(int age){
if(age<18)
throw new Arithmetic...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Syntax of throws keyword:
void method_name() throws except...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

}
catch(IOException exp){
System.out.println("exception ha...
Exception Handling in Java

Manu M,manumanjunatha.mm@gmail.com

Custom Exception
If you are creating your own Exception th...
Upcoming SlideShare
Loading in …5
×

Exception handling

1,018 views

Published on

Exception Handling,Exception Handlingin Java

Published in: Education
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,018
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

Exception handling

  1. 1. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com The satisfaction and euphoria that accompany the successful completion of any task would be incomplete without mentioning the people who have made it possible, because “success is the epitome of hard work and perseverance but stead-fast of all is encouraging guidance”. So with deep gratitude i acknowledge My Parents and My Teacher, Ravi kumar Hadagali- Chairman at Cluster Software Solutions . Manu M 1
  2. 2. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Exception Handling Errors: It is a runtime error which will cause the program to terminate. You cannot handle it. Error will terminate the program. Actually, these are not exceptions at all, but Sun Microsystems says it is a type of Exception .Thses are problems that arise beyond the control of the user or the programmer. e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc. errors are often ignored when designing and writing Java applications,Why? errors are typically ignored in your code because you can rarely do anything about an error, even if you wanted your program to fix the problem. For example, if a stack overflow occurs, an error will arise. However, because you are out of memory, your program will be unable to continue executing. Any code you have written that attempts to fix the problem won’t get a chance to execute anyway, so errors are often ignored when designing and writing Java applications. Exceptions It is a runtime error which can cause the program to terminate. We can handle the exception and if handeled program does not terminate and execution continues normally. Exception is an object thrown by a method. e.g ArithmeticException int a=50/0;//ArithmeticException NumberFormatException boolean b=true; int i=Integer.parseInt(s); NullPointerException Employee e1=null; System.out.println(e.name);//NullPointerException 2
  3. 3. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com ArrayIndexOutOfBoundsException int a[]=new int[10]; System.out.println(a[20]); //ArrayIndexOutOfBoundsException Checked exceptions:If Checked exception is present in program ,then before doing anything to program we need to do something to exception. Since we have to do Something to exception before doing anything to program it is a Checked exceptions. Unchecked exceptions : If Unchecked exception is present in program ,then we can do anything to program without doing anything to exception. sSince we can proceed with program execution without doing anything to exception it is a Unchecked exceptions. Checked exceptions Definition Hierarchy Ingnorance Compilation Handling verification JVM Propagation Caught/ uncaught Throws clause Scenario Overriding Unchecked exceptions Any exception which is must to handle or catch it, while writing the program is called checked exception. They are all subclasses of Exception Must be formally acknowledged in the program one way or another. If your code fails to either handle a checked exception or declare that it is thrown, your code won't compile. Checked Exception in Java is those Exceptions whose handling is verified during Compile time. Any exception which is not mandatory to handle or catch it, while writing the program or executing the program is called unchecked exception. They are all subclasses of RuntimeException. Unchecked exceptions can be ignored completely in the code if desired. If your code fails to either handle a Unchecked exception or declare that it is thrown, your code will compile. JVM enforces developer to handle or catch it: By default Unchecked Exceptions are forwarded in calling chain (propagated). They are also called as caught exceptions JVM does not enforce developer to handle or catch it: By default, Checked Exceptions are not forwarded in calling chain (propagated). They are also called as uncaught exceptions. The throws clause on a method header must be included for checked exceptions that are not caught and handled in the method. CheckedException represent scenario with higher failure rate The throws clause on a method header is not mandatory to be included for unchecked exceptions that are not caught and handled in the method. UnCheckedException are mostly programming mistakes.   Unchecked Exception in Java is those Exceptions whose handling is not verified during Compile time. If the superclass method does not declare any exception o If the superclass method does not declare any exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception. If the superclass method declares exception o If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. use Expected but unpreventable:  you try reading a file but someone deletes it between the time you check if it exists and the time the read operation begins. By declaring a checked exception, you are telling the caller to anticipate this failure so that giving the user an opportunity to try another filename.  You are uploading a file,but while uploading if network connection is lost. By declaring a checked exception, you are telling the caller to anticipate this failure so that giving the user an opportunity to try a onther attempt or resume from the point where stopped. 1. User input validation: User is expected to enter a digit ,but he enters alphabet 2. Business logic or rules validation : User is not supposed to violet the rule of dividing a number by zero. Checked exceptions cannot be foreseen by the programmer. But it is the duty of programmer to think from all dimensions about different possibilities that may accur. 3
  4. 4. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Flow of Control of Exceptions Class A{ Class method3() void A { { Void method1() //exception occurred here { } Void method2() void method2() { { Void method3() method3(); { } void method1() //exception } { } method2(); } } } } method3 method2 method1 main Method call stack caller of method3() caller of method2() caller of method1() 1) If method3() throws an exception, method3() is popped off the call stack, and the exception is thrown down to method2(). With an exception heading its way, method2 () has three choices: ■■ Catch the exception so that it does not go any further down the call stack. ■■ Catch the exception, then throw it back down the call stack. ■■ Not catch the exception, thereby causing method1() to be popped off the call stack, with the exception continuing down the call stack to main(). 2) If method2() doesn’t catch the exception, method2() is popped off the call stack, and the exception is thrown down to method1(). With an exception heading its way, method2 () has three choices: ■■ Catch the exception so that it does not go any further down the call stack. ■■ Catch the exception, then throw it back down the call stack. ■■ Not catch the exception, thereby causing method1() to be popped off the call stack, with the exception continuing down the call stack to main(). 3) If method1() doesn’t catch the exception, method1() is popped off the call stack, and the exception is thrown down to main method. Like this flow of control continues down the call stack, no matter how many methods appear on the call stack. Each method further down the call stack either catches the exception and stops this process, catches the exception and throws it again, or simply does nothing and lets the exception fall through to the next method. 4) When an exception reaches the bottom of a call stack to the main method , main() ignores the exception as well, main() is popped off the call stack. The exception is then passed on to the JVM, JVM provides a default exception handler and the JVM prints out the stack trace and terminates. Note: We can print this stack trace yourself with any exception you catch by using the printStackTrace() method of the Throwable class. 4
  5. 5. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Hierarchy of Exception classes Exception Handling in Java Five keywords used in Exception handling: 1. 2. 3. 4. 5. try catch finally throw throws try block  Enclose the code that might throw an exception in try block. Code within a try/catch block is referred to as protected code  It must be used within the method and must be followed by either catch or finally block.  If exception doesn’t occurs inside try block, then catch block will be skipped.  If exception occurs inside try block then remaining statements will be skipped in try block ,contoll jumps to catch block. Syntax of try with catch block try{ ... }catch(Exception_class_Name reference){} Syntax of try with finally block try{ ... }finally{} 5
  6. 6. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com catch block  Catch block is used to handle the Exception. It must be used after the try block.  Acatch 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. If you say you want to catch a NullPointerException and an ArithmeticException occurs, you will not catch the ArithmeticException.  If you say you want to catch an Exception, then you will catch every exception that might arise. Remember, all exceptions are child classes of Exception, so through polymorphism, all exceptions are of type Exception. package com.manum.hassan; public class ExceptionHandling { public static void main(String[] args) { try{ int data=50/0; }catch(ArithmeticException e) { System.out.println(e); e.printStackTrace(); } System.out.println("rest of the code..."); } } Output: java.lang.ArithmeticException: / by zero rest of the code... java.lang.ArithmeticException: / by zero at com.manum.hassan.ExceptionHandling.main(ExceptionHandling.java:6) without exception handling public class ExceptionHandling { public static void main(String[] args) { int data=50/0; System.out.println("rest of the code..."); } } Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at com.manum.hassan.ExceptionHandling.main(ExceptionHandling.java:19) Note:"rest of the code..." is not printed Tyr/catch block can return a value class A{ int a; A(int a){this.a=a;} boolean meth(){ try{ int val=50/a; return true; }catch(ArithmeticException e) { return false; We can return value in try or catch block 6
  7. 7. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com } No statements allowed here as no statements are allowed after return statement } } public class ExceptionHandling { public static void main(String[] args) { A a=new A( Integer.parseInt(args[0])); boolean val=a.meth(); System.out.println(val); } } Output: true (If args[0]= any non zero number) false (If args[0]= 0) Here meth() method(which is having exception) is called inside main method .Hence main method is a caller method. If exception occurs in meth() and that exception is not handled inside meth() then exception is thrown onto caller method i.e. main method. Multiple catch block:  One try block can have multiple catch statements. In some cases, more than one exception can occur in a try block, But always only one type of an exception object will be created at a time. To handle such situations one try block can have multiple catch statements. But since always only one type of an exception object will be created in the try block ,only one catch block gets executed.  When an exception is thrown, each catch statement is inspected in order and the first one which matches that exception type will get executed.  All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch for Exception .  Even though class Exception can handle all the exceptions, it is always advisable to write the specific type of Exception in the catch block. Because after catching the Exception, next we have to check the type of Exception which has occurred, and then write the logic to fix the error for that exception. class ExceptionHandling{ public static void main(String args[]){ try{ System.out.println("going to divide"); int b =39/ Integer.parseInt(args[0]);; int a[]=new int[1]; a[5]=4; } catch(ArrayIndexOutOfBoundsException e){System.out.println("ArrayIndexOutOfBoundsException is Handeled");} catch(ArithmeticException e){System.out.println("ArithmeticException is Handeled");} catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } } If exception occurs here then remaining statements inside try block will be skipped. If those statements are very much important for us to execute then we can use nested try/catch block. 7
  8. 8. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Nested try block: try block within a try block is known as nested try block. 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 Syntax: .... try { statement 1; statement 2; try { statement 1; statement 2; } catch(Exception e) { } } catch(Exception e) { } .... Example: class ExceptionHandling{ public static void main(String args[]){ try{ try{ System.out.println("going to divide"); int b =39/0; }catch(ArithmeticException e){System.out.println(e);} try{ int a[]=new int[5]; a[5]=4; }catch(ArrayIndexOutOfBoundsException e){System.out.println(e);} System.out.println("other statement"); }catch(Exception e){System.out.println("handeled");} System.out.println("normal flow.."); } } Output: going to divide java.lang.ArithmeticException: / by zero java.lang.ArrayIndexOutOfBoundsException: 5 other statement normal flow.. finally The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc. 8
  9. 9. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Note: Before terminating the program, JVM executes finally block(if any). finally must be followed by try or catch block. Why use finally block?  finally block can be used to put "cleanup" code such as closing a file,closing connection etc.(to clear method level resources). case 1 Program in case exception does not occur class ExceptionHandling{ public static void main(String args[]){ try{ int data=25/5; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Output: 5 finally block is always executed rest of the code... case 2 Program in case exception occured but not handled class ExceptionHandling{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(NullPointerException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } 9
  10. 10. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com OutPut: finally block is always executed Exception in thread "main" java.lang.ArithmeticException: / by zero at com.manum.hassan.ExceptionHandling.main(ExceptionHandling.java:93) case 3 Program in case exception occured and handled class ExceptionHandling{ public static void main(String args[]){ try{ int data=25/0; System.out.println(data); } catch(ArithmeticException e){System.out.println(e);} finally{System.out.println("finally block is always executed");} System.out.println("rest of the code..."); } } Output: java.lang.ArithmeticException: / by zero finally block is always executed rest of the code... Rule: For each try block there can be zero or more catch blocks, but only one finally block. Note: The finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort). Q What are the different conditions that a method gets terminated? A There are three conditions or reasons for which method gets terminated. a) return keyword. (control returns to calling line of the caller method) b) An exception occurs (control returns to the catch block of the caller method) c) System.exit() method (program terminates) throw    The throw keyword is used to explictily throw an exception. When one method calls another method (Either main method invoking other methods or other method invoking some other method) exception object is thrown to the caller method. Execution stops immediately after the throw statement and any subsequent statements are not executed. We can throw either checked or uncheked exception.( subclasses of class Throwable) The throw keyword is mainly used to throw custom exception(generally). Example of throw keyword In this example, we have created the validate method that takes integer value as a parameter.This value is treated as age of a person. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message welcome to vote. 10
  11. 11. Exception Handling in Java For age greater than 18 class Excep13{ void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } } class ExceptionHandling{ public static void main(String args[]){ Excep13 obj= new Excep13(); obj.validate(19); System.out.println("rest of the code..."); } } Output: welcome to vote rest of the code... Manu M,manumanjunatha.mm@gmail.com For age less than 18 class Excep13{ void validate(int age){ if(age<18) throw new ArithmeticException("not valid"); else System.out.println("welcome to vote"); } } class ExceptionHandling{ public static void main(String args[]){ Excep13 obj= new Excep13(); obj.validate(13); System.out.println("rest of the code..."); } } Output: Exception in thread "main" java.lang.ArithmeticException: not valid at com.manum.hassan.Excep13.validate(ExceptionHandling. java:119) at com.manum.hassan.ExceptionHandling.main(Ex ceptionHandling.java:127) Throwing same exception which is caught is known as Rethrowing an exception. catch (WhateverException e) { throw e; } throws In the above program of voting we want exception to occur mandatorily if age is below 18, otherwise any person with age below 18 can vote. In the program we used ArithmeticException which is unchecked exception. But if any checked exception is used the program will not compile at all. So in order to compile the program and to arise checked exception during run time we use throws keyword to declare exception. If I try to withdraw more money than I have in my checking account, exception should occur and should inform me that I am trying to overdraft .If exception doesn’t occurs and fails to stop me from ignoring my overdraft then i can just go right on spending more money and then plead ignorance when my overdraft statement comes in the mail. I can tell the bank that I didn’t check the return value of the withdraw() method.In this case if checked exception is used then program will not compile at all. So in order to compile the program and to arise checked exception during run time we use throws keyword to declare exception. When do you handle an exception and when do you declare an exception? The answer is based on design decisions. Do you want a method to deal with a problem, or do you want the problem to be passed on to the caller of the method? Suppose that I walk into my bank and make a deposit (by invoking a deposit() method), but the teller is having problems with his computer. That should not be my problem. In this case, the deposit() method should handle this exception and fix the problem without notifying me, the caller of the method. If I am in the middle of a deposit and the bank’s computer system fails, that might be my problem. In that case, I want to be informed that my deposit did not successfully go through. The deposit() method can tell me that the transaction was unsuccessful by throwing an exception back to me. 11
  12. 12. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Syntax of throws keyword: void method_name() throws exception_class_name{ ... } class Excep13 { void validate(int age) throws IOException{ if(age<18) throw new IOException("not valid"); else System.out.println("welcome to vote"); } } class ExceptionHandling{ public static void main(String args[])throws IOException{ Excep13 obj= new Excep13(); obj.validate(13); System.out.println("rest of the code..."); } } Output: (If age greater than 18) welcome to vote rest of the code... (If age less than 18) Exception in thread "main" java.io.IOException: not valid at com.manum.hassan.Excep13.validate(ExceptionHandling.java:140) at com.manum.hassan.ExceptionHandling.main(ExceptionHandling.java:148) Que) Which exception should we declare? Ans) checked exception only, because:  unchecked Exception: under your control so correct your code.  error: beyond your control e.g. you are unable to do anything if there occurs VirtualMachineError or StackOverflowError. Note:Generally we declare only checked exception, but declaring unchecked exception will not give any compilation error. Advantage of throws keyword: Checked Exception can be propagated (forwarded in call stack). import java.io.IOException; class ExceptionHandling{ void method3() throws IOException { throw new IOException("device error");//checked exception } void method2 ()throws IOException { method3(); } void method1() { try{ method2(); 12
  13. 13. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com } catch(IOException exp){ System.out.println("exception handled"); } } public static void main(String args[]) { ExceptionHandling obj=new ExceptionHandling(); obj.method1(); System.out.println("normal flow..."); } } Output: exception handled normal flow... In the above program following sequence happens 1. 2. 3. 4. 5. 6. main method is a caller of method1() method1() is is a caller of method2() method2() is is a caller of method3() method3() throws exception to caller, method2() method2() throws exception to caller, method1() method1() handles exception using try catch . In the above program if method is void method1() throws IOException { try{ method2(); } catch(IOException exp){ System.out.println("exception handled"); } } Then main method should be as public static void main(String args[]) { . . . . throws IOException Difference between throw and throws: throw throw is used to explicitly throw an exception. Syntax throw <instance of any exception class>; Can throw only one exception throws throws is used to declare an exception. Syntax <method signature> throws <exception class name> , <exception class name> …. Can declare multiple exception 13
  14. 14. Exception Handling in Java Manu M,manumanjunatha.mm@gmail.com Custom Exception If you are creating your own Exception that is known as custom exception or user-defined exception. Q How to write user defined Exception ? A Use following steps  The class must extend any exception class.  If you want to create a checked exception extend class Exception.  If you want to create an unchecked exception extend class RuntimeException. class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } } class ExceptionHandling{ static void validate(int age)throws InvalidAgeException{ if(age<18) throw new InvalidAgeException("not valid"); else System.out.println("welcome to vote"); } public static void main(String args[]){ try{ validate(13); }catch(Exception m){System.out.println("Exception occured: "+m);} System.out.println("rest of the code..."); } } Output: Exception occured: com.manum.hassan.InvalidAgeException: not valid rest of the code... Exception Handling with Method Overriding There are many rules if we talk about method overriding with exception handling. The Rules are as follows:  If the superclass method does not declare any exception o If the superclass method does not declare any exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.  If the superclass method declares exception o If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. 14

×