Java Exception Handling

Views:
 
Category: Education
     
 

Presentation Description

Java Exception Handling Tutorial

Comments

Presentation Transcript

Exception Handling:

5/8/2015 www.sunrays.co.in 1 Exception Handling throw catch SUNRAYS Technologies ABC square, Sambhaji square, Nigadi Pradhikaran , PUNE-44, Maharashtra, INDIA Tel +91 77750-85756 212 President Tower, 6/2 South Tukogunj , INDORE-1 , MP, INDIA , Tel +91 731-4249244, Cell : +91-98273 60504 314, 3rd Floor, Saffron Complex, Fatehgunj , VADODARA-2, Gujarat, INDIA Tel : +91 85111-41515 Email : [email protected] URL : www.sunrays.co.in , www.sunraystechnologies.com

Our Books – www.sunilbooks.com:

Our Books – www.sunilbooks.com 5/8/2015 www.sunrays.co.in 2

Slide3:

5/8/2015 www.sunrays.co.in 3 PUNE | INDORE | VADODARA | RAIPUR www.sunrays.co.in [email protected]

Exception :

5/8/2015 www.sunrays.co.in 4 Exception Exceptional (that is error) condition that has occurred in a piece of code of Java program.

Exception :

5/8/2015 www.sunrays.co.in 5 Exception It will cause abnormal termination of program or wrong execution result. Java provide an exception handling mechanism to handle exceptions. Exception handling will improve the reliability of application program. Java creates different type of objects in case of different exceptional conditions that describe the cause of exception.

Exception Definition:

5/8/2015 www.sunrays.co.in 6 Exception Definition Treat exception as an object All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a programmer can make new exception class by extending the Exception class which is subclass of Throwable class.

Hierarchical Structure of Throwable Class:

5/8/2015 www.sunrays.co.in 7 Hierarchical Structure of Throwable Class Object Throwable Error Exception RuntimeException ... ... ...

Exception Types:

5/8/2015 www.sunrays.co.in 8 Exception Types Error Class Abnormal conditions those can NOT be handled are called Errors Exception Class Abnormal conditions those can be handled are called Exceptions

Java Exception class hierarchy:

5/8/2015 www.sunrays.co.in 9 Java Exception class hierarchy Object Error Throwable Exception LinkageError VirtualMachoneError ClassNotFoundException FileNotFoundException IOException AWTError … AWTException RuntimeException … ArithmeticException NullPointerException IndexOutOfBoundsException Unchecked Checked NoSuchElementException … : try-catch block is mandatory : try-catch block is optional

Exception Handling:

5/8/2015 www.sunrays.co.in 10 Exception Handling Exception handling is managed by five keywords try, catch, throw, throws , and finally . Exceptions can be generated by Java “run-time system” are called System-generated exceptions. It is automatically raised by Java run-time system. Your code are called Programmatic Exceptions. It is raised by throw keyword. When an exceptional condition arises, an object is created that contains exception description. Handling is done with help of try-catch-finally block . Exception raised in try block is caught by catch block. Block finally is optional and always executed.

try-catch-finally Statement :

5/8/2015 www.sunrays.co.in 11 try-catch-finally Statement try { // code } catch (ExceptionType1 identifier) { // alternate flow 1 } catch (ExceptionType2 identifier) { // alternate flow 2 } finally { //Resource release statements like close file , //close N/W connection, //close Database connection, Release memory cache }

Uncaught Exception:

Uncaught Exception public class TestArithmetic { public static void main(String[] args) { int k = 0; int i = 15; double div = i / k; System.out.println("Div is " + div); }} 5/8/2015 www.sunrays.co.in 12 Output java.lang.ArithmeticException: / by zero at TestArithmetic .main(TestArithmetic .java:5) JVM detects that number is divided by zero that will produce infinity. Since infinity can be stored that is why it makes a new exception object and then throws this exception.

Exception Output:

Stack Trace Exception Output 5/8/2015 www.sunrays.co.in 13 Exception class Exception Message Exception Line Number JVM detects the attempt to divide by zero, it makes new exception object java.lang.ArithmeticException : / by zero at TestArithmetic .main( TestArithmetic .java:5 )

Handle Exception:

Handle Exception public class TestArithmetic { public static void main(String[] args ) { int k = 0; int i = 15; try { double div = i / k; System.out.println ("Div is " + div); } catch ( ArithmeticException e) { System.out.println (“ Divided by Zero"); } }} 5/8/2015 www.sunrays.co.in 14 Output Divided by Zero Notice that the call to println( ) inside the try block is never executed

Flow of execution:

Flow of execution try { a b //Throw Exception c } catch (Exception e) { d e } finally { f } Normal Flow a b c f Exceptional Flow a b d e f 5/8/2015 www.sunrays.co.in 15

Exception methods:

Exception methods Object received in catch block contains two key methods e.getMessage (); //displays error message. / by zero e.printStackTrace (); //displays complete trace of exception java.lang.ArithmeticException : / by zero at TestArithmetic .main( TestArithmetic .java:5 ) 5/8/2015 www.sunrays.co.in 16

Multiple catch blocks :

Multiple catch blocks More than one exception could be raised by a single try block. To handle this type of situation, you can specify two or more catch blocks String name = “Vijay” ; try { System. out.println ("Length of name is " + name.length ()); System. out.println ("Charter at 7th position is " + name.charAt (6)); } catch ( StringIndexOutOfBoundsException e) { System. out.println ("String abhi choti he!!"); } catch ( NullPointerException e) { System. out.println (“ Sundar sa nam nahi he!"); } finally { System. out.println (“ Pandit hu me"); } 5/8/2015 www.sunrays.co.in 17

Multiple catch blocks (cont. ) :

Multiple catch blocks (cont. ) More than one exception could be raised by a single try block. To handle this type of situation, you can specify two or more catch blocks String name = null ; try { System. out.println("Length of name is " + name.length()); System. out.println("Charter at 7th position is " + name.charAt(6)); } catch (StringIndexOutOfBoundsException e) { System. out.println("String abhi choti he!!"); } catch (NullPointerException e) { System. out.println(“Sundar sa nam nahi he!"); } finally { System. out.println(“Pandit hu me"); } 5/8/2015 www.sunrays.co.in 18

Parent catch:

Parent catch String name = “Vijay” ; try { System. out.println("Length of name is " + name.length()); System. out.println("Charter at 7 position is " + name.charAt(6)); } catch (StringIndexOutOfBoundsException e) { System. out.println("String abhi choti he!!"); } catch (RuntimeException e) { System. out.println(“Sundar sa nam nahi he!"); } finally { System. out.println(“Pandit hu me"); } 5/8/2015 www.sunrays.co.in 19

Generic Catch :

Generic Catch A catch block of Parent Class can handle exceptions of its sub classes. It can be used as a generic catch to handle multiple exceptions in down hierarchy. String name = “Vijay” ; try { System. out.println("Length of name is " + name.length()); System. out.println("Charter at 7th position is " + name.charAt(6)); } catch (Exception e) { System. out.println(“Error ” + e.getMessage() ); } 5/8/2015 www.sunrays.co.in 20

Order of catch blocks: Parent & Child:

Order of catch blocks: Parent & Child Catch block of a Child class must come first in the order, if Parent’s class catch does exist. String name = “Vijay” ; try { System. out.println("Length of name is " + name.length()); System. out.println("Charter at 7 position is " + name.charAt(6)); } catch (StringIndexOutOfBoundsException e) { System. out.println("String abhi choti he!!"); } catch (RuntimeException e) { System. out.println(“Error “ + e,getMessage()); } 5/8/2015 www.sunrays.co.in 21

System-Defined Exception:

5/8/2015 www.sunrays.co.in 22 System-Defined Exception It is raised implicitly by system because of illegal execution of program when system cannot continue program execution any more. It is created by Java System automatically. It is extended from Error class or RuntimeException class.

System-Defined Exception:

5/8/2015 www.sunrays.co.in 23 System-Defined Exception IndexOutOfBoundsException : When beyond the bound of index in the object which use index, such as array, string, and vector ArrayStoreException : When assign object of incorrect type to element of array NegativeArraySizeException : When using a negative size of array NullPointerException : When refer to object as a null pointer SecurityException : When violate security. Caused by security manager IllegalMonitorStateException : When the thread which is not owner of monitor involves wait or notify method

Programmer-Defined Exception :

5/8/2015 www.sunrays.co.in 24 Programmer-Defined Exception Programmer can create custom exceptions by extending Exception or its sub-classes. Exceptions are raised by programmer with help of throw keyword

Programmer Exception Class:

Programmer Exception Class class LoginException extends Exception { //Custom exception public LoginException () { super("User Not Found") ; } } class UserClass { //Raise custom exception LoginException e = new LoginException (); // ... if ( val < 1) throw e; } } Exception is raised by throw keyword. 5/8/2015 www.sunrays.co.in 25

Exception Occurrence:

5/8/2015 www.sunrays.co.in 26 Exception Occurrence Raised implicitly by system Raised explicitly by programmer throw Statement throw new LoginException(); Throwable class or its sub class

Exception propagation:

5/8/2015 www.sunrays.co.in 27 Exception propagation If there is no catch block to deal with the exception, it is propagated to calling method. Unchecked exceptions are automatically propagated. Checked exceptions are propagated by throws keyword. returntype methodName(params) throws e1, ... ,ek { } Called method Calling method

Exception propagation ( Cont.):

Exception propagation ( Cont.) public static void main(String[] args ) { try { authenticate (“ vijay ”); } catch ( LoginException exp) { System.out.println (“Invalid Id/ Passwod ”); } } public static void authenticate ( String login) throws LoginException { If( !“ admin”.equals (login)){ LoginException e = new LoginException (); throw e; } } 5/8/2015 www.sunrays.co.in 28

Example Source Code :

Example Source Code 5/8/2015 www.sunrays.co.in 29 https://github.com/sunilbooks/SelfLearnJava

Thank You:

Thank You 5/8/2015 www.sunrays.co.in 30 If you have any questions, feel free to contact us Email : [email protected] URL : www.sunrays.co.in Next topic “Collections Framework”