SlideShare une entreprise Scribd logo
1  sur  28
Disclaimer:This presentation is prepared by trainees of baabtra
as a part of mentoring program. This is not official document of
baabtra –Mentoring Partner
Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt . Ltd
Exception Handling



            vineethmenon18@gmail.com
Exception Handling in Java

Types of Errors
1.Compile time
All syntax errors identified by java compiler.
No class file is created when this occurs.
So it is necessary to fix all compile time errors for successful
compilation.
Egs:
Missing of semicolon,
use of = instead of ==




                                                                   4
Exception Handling in Java

2.Run time
Some pgms may not run successfully due to wrong logic or
errors like stack overflow.


Some of the Common run time errors are:
      Division by 0
      Array index out of bounds
      Negative array size etc..




                                                           5
Exception Handling in Java

Exception is a condition caused by a run time error in the program.
When the java interpreter identifies an error such as division by 0
it creates an Exception object and throws it

Definition:

An exception is an event, which occurs during the execution of a
program, that disrupts the normal flow of the program's
instructions.
Is defined as a condition that interrupts the normal flow of
operation within a program.




                                                                 6
Exception Handling in Java

Java allows Exception handling mechanism to handle various
exceptional conditions. When an exceptional condition occurs, an
exception is said to be thrown.

For continuing the program execution, the user should try to catch
the exception object thrown by the error condition and then display
an appropriate message for taking corrective actions. This task is
known as Exception handling




                                                                 7
Exception Handling in Java


This mechanism consists of :

1.   Find the problem(Hit the Exception)
2.   Inform that an error has occurred(Throw the    Exception)
3.   Receive the error Information(Catch the Exception)
4.   Take corrective actions(Handle the Exception)




                                                                 8
Exception Handling in Java

In Java Exception handling is managed by 5 key words:
try
catch
throw
throws
finally




                                                        9
Exception Handling in Java

In Java Exception handling is managed by 5 key words:
try
catch
throw
throws
finally




                                                        10
Exception Handling in Java
  Exception Hierarchy


 Package java.lang


                                 Throwable


                     Exception               error



InterruptedException        RuntimeException
(checked exception)         (unchecked exception)



                                                     11
Exception Handling in Java
 Unchecked exception:
    These exception need not be included in an
     method’s throws list
    The compiler does not check to see if a method
     handles or throws these exception
    these are subclasses of RuntimeException
    The compiler doesn't force client programmers
     either to catch the exception or declare it in a
     throws clause.
    Class Error and its subclasses also are unchecked.
 Checked exception:
  Must be included in an method’s throws list if that method can
   generate one of those exceptions and does not handle it itself
  These exception defined by java.lang




                                                                12
Exception Handling in Java
     Java’s unchecked RuntimeException subclasses defined in java.lang
Exception                              Meaning

ArithmeticException                    Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsException         Array index is out-of-bounds
ArrayStoreException                    Assignment to an array element of an incompatible type
ClassCastException                     Invalid cast
EnumConstantNotPresentException        An attempt is made to use an undefined enumeration
                                       value
IllegalArgumentException               Illegal argument used to invoke a method
IllegalMonitorStateException           Illegal monitor operation, such as waiting on an unlocked
                                       thread
IllegalStateException                  Environment or application is in incorrect state
IllegalThreadStateException            Requested operation not compatible with current thread
                                       state
IndexOutOfBoundsException              Some type of index is out-of-bounds
NegativeArraySizeException             Array created with a negative size

                                                                                           13
Exception Handling in Java

Exception                         Meaning
NullPointerException              Invalid use of a null reference
NumberFormatException             Invalid conversion of a string to a numeric format
SecurityException                 Attempt to violate security
StringIndexOutOfBoundsException   Attempt to index outside the bounds of a string
TypeNotPresentException           Type not fount
UnsupportedOperationException     An unsupported operation was encountered




                                                                                       14
Exception Handling in Java
Java’s checked Exception defined in java.lang

Exception                               Meaning
ClassNotFoundException                  Class not found
CloneNotSupportedException              Attempt to clone an object that does not implement the
                                        Cloneable interface
IllegalAccessException                  Access to a class is denied
InstantiationException                  Attempt to create an object of an abstract class or
                                        interface
InterruptedException                    One thread has been interrupted by another thread
NoSuchFieldException                    A requested field does not exist
NoSuchMethodException                   A requested method does not exist




                                                                                              15
Exception Handling in Java

class Ex{
       public static void main(String args[]){
       int a=0;
              int b=2/a;
       }
}
Java.lang.ArithmeticException: / by zero at Ex.main




                                                      16
Exception Handling in Java
try & catch
                       try Block


                     Statement that
                    causes Exception




                     Catch Block


                     Statement that
                    causes Exception




                                           17
Exception Handling in Java

  try{
         Statement:
  }
  catch(Exception-type e){
         statement;
  }




                             18
Exception Handling in Java
class Ex{
   public static void main(String args[]){
        int d,a;
        try{
           d=0;
           a=10/d;                           Once an exception is
           System.out.println("from try");   thrown , program control
        }catch(ArithmeticException e)        transfers out of the try
        {                                    block into the catch block.
System.out.println("divsn by Zero");         Once the catch statement
        }                                    is executed pgm control
      System.out.println("after catch");     continues with the next
   }                                         line following the entire
}                                            try/catch mechanism.




                                                                    19
Exception Handling in Java
We can display the description of an Exception in a println
statement by simply passing the exception as an argument.




  catch(ArithmeticException ae){
         System.out.println(“Exception:”+ae);
  }
  o/p
  Exception:java.lang.ArithmeticException: /by zero




                                                              20
Exception Handling in Java
          Common Throwable methods

• getMessage(); All throwable objects can have an
  associated error message. Calling this message will
  return the message if one present.

• getLocalizedMessage(); gets the localized version of
  error message.

• printStackTrace(); sends the stack trace to the system
  console. This is a list of method calls that led to the
  exception condition. It includes line number and file
  names too. Printing of the stack trace is the default
  behavior of a runtime exception when u don’t catch it
  ourselves.
                                                            21
Exception Handling in Java

Multiple catch Statement
some cases, more than one exception could be raised by
a single piece of code.
such cases we can specify two or more catch
clauses, each catching a different type of exception.
when an exception thrown, each catch statement is
inspected in order, and the first one whose type matches
that of the exception is executed.
After 1 catch statement is executed, the others are
bypassed and execution continues after the try/catch
block.



                                                           22
Exception Handling in Java


class Ex{
public static void main(String
                         args[]){
        int d,a,len;
        try{
              len=args.length;
                 a=10/len;
                 int c[]={1};     catch(ArithmeticException e){
                 c[10]=23;               System.out.println("divsn by
        }                                               Zero"+e);
                                  }
                                  catch(ArrayIndexOutOfBoundsExcept
                                                                ion ae){
                                  System.out.println("Array index"+ae);
                                  }
                                  System.out.println("after catch");
                                  }
                                  }                                   23
Exception Handling in Java

In multiple catch statement exception subclasses must come
before any of their superclasses.
Because a catch statement that uses a superclass will catch
exception of that type plus any of its subclasses.
Thus a subclass would never be reached if it came after its
superclass.

Further java compiler produces an error
unreachable code.




                                                              24
Exception Handling in Java

finally
It creates a block of code that will be executed after try/catch
block has completed and before the code following try/catch
block.
It will execute whether or not an exception is thrown
finally is useful for:
   •Closing a file
   •Closing a result set
   •Closing the connection established with database
This block is optional but when included is placed after the last
catch block of a try

                                                             25
Exception Handling in Java

Form:
try
                                   try block
{}
catch(exceptiontype e)
{}
finally
                         finally               Catch block
{}



                                                  finally




                                                             26
• If this presentation helped you, please visit
  our page facebook.com/baabtra and like it.
  Thanks in advance.

• www.baabtra.com | www.massbaab.com |ww
  w.baabte.com
Contact Us

Contenu connexe

Tendances (20)

Exceptions handling notes in JAVA
Exceptions handling notes in JAVAExceptions handling notes in JAVA
Exceptions handling notes in JAVA
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
JAVA - Throwable class
JAVA - Throwable classJAVA - Throwable class
JAVA - Throwable class
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
exception handling
exception handlingexception handling
exception handling
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception
Java exception Java exception
Java exception
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in Java
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-Knows
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & MultithreadingB.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
B.Sc. III(VI Sem) Advance Java Unit1: Exception Handling & Multithreading
 

En vedette

Field Service Forum 2016
Field Service Forum 2016Field Service Forum 2016
Field Service Forum 2016Copperberg
 
Meet Nordic IT Security Advisory board, David Jacoby
Meet Nordic IT Security Advisory board, David JacobyMeet Nordic IT Security Advisory board, David Jacoby
Meet Nordic IT Security Advisory board, David JacobyCopperberg
 
Nordic IT Security Forum 2015 Agenda
Nordic IT Security Forum 2015 AgendaNordic IT Security Forum 2015 Agenda
Nordic IT Security Forum 2015 AgendaCopperberg
 
TOP5 facts about Mobile Payments
TOP5 facts about Mobile PaymentsTOP5 facts about Mobile Payments
TOP5 facts about Mobile PaymentsCopperberg
 
I-Gaming Forum 2015 Post Event Report
I-Gaming Forum 2015 Post Event ReportI-Gaming Forum 2015 Post Event Report
I-Gaming Forum 2015 Post Event ReportCopperberg
 

En vedette (20)

Cpu and execution of instruction.
Cpu and execution of instruction.Cpu and execution of instruction.
Cpu and execution of instruction.
 
Jvm
JvmJvm
Jvm
 
Field Service Forum 2016
Field Service Forum 2016Field Service Forum 2016
Field Service Forum 2016
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Meet Nordic IT Security Advisory board, David Jacoby
Meet Nordic IT Security Advisory board, David JacobyMeet Nordic IT Security Advisory board, David Jacoby
Meet Nordic IT Security Advisory board, David Jacoby
 
Database normalisation
Database normalisationDatabase normalisation
Database normalisation
 
Claas diagram
Claas diagramClaas diagram
Claas diagram
 
Claas diagram
Claas diagramClaas diagram
Claas diagram
 
Nordic IT Security Forum 2015 Agenda
Nordic IT Security Forum 2015 AgendaNordic IT Security Forum 2015 Agenda
Nordic IT Security Forum 2015 Agenda
 
Database normalization
Database normalizationDatabase normalization
Database normalization
 
Cms
CmsCms
Cms
 
OOP in java
OOP in javaOOP in java
OOP in java
 
TOP5 facts about Mobile Payments
TOP5 facts about Mobile PaymentsTOP5 facts about Mobile Payments
TOP5 facts about Mobile Payments
 
I-Gaming Forum 2015 Post Event Report
I-Gaming Forum 2015 Post Event ReportI-Gaming Forum 2015 Post Event Report
I-Gaming Forum 2015 Post Event Report
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
LAI International | A Manufacturing Capabilities Overview
LAI International | A Manufacturing Capabilities OverviewLAI International | A Manufacturing Capabilities Overview
LAI International | A Manufacturing Capabilities Overview
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 

Similaire à Exeption handling

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handlingkamal kotecha
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptxprimevideos176
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptionsİbrahim Kürce
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptxNagaraju Pamarthi
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
Unit5 java
Unit5 javaUnit5 java
Unit5 javamrecedu
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javachauhankapil
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertionsphanleson
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in javajunnubabu
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.pptRanjithaM32
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in JavaAnkit Rai
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception HandlingAshwin Shiv
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handlingKuntal Bhowmick
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaKavitha713564
 

Similaire à Exeption handling (20)

Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
Exception Handling.pptx
Exception Handling.pptxException Handling.pptx
Exception Handling.pptx
 
OCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 ExceptionsOCA Java SE 8 Exam Chapter 6 Exceptions
OCA Java SE 8 Exam Chapter 6 Exceptions
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Unit5 java
Unit5 javaUnit5 java
Unit5 java
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Itp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & AssertionsItp 120 Chapt 18 2009 Exceptions & Assertions
Itp 120 Chapt 18 2009 Exceptions & Assertions
 
Comp102 lec 10
Comp102   lec 10Comp102   lec 10
Comp102 lec 10
 
Exceptions handling in java
Exceptions handling in javaExceptions handling in java
Exceptions handling in java
 
UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Java Exception.ppt
Java Exception.pptJava Exception.ppt
Java Exception.ppt
 
Exception handling in Java
Exception handling in JavaException handling in Java
Exception handling in Java
 
Java SE 11 Exception Handling
Java SE 11 Exception HandlingJava SE 11 Exception Handling
Java SE 11 Exception Handling
 
Class notes(week 8) on exception handling
Class notes(week 8) on exception handlingClass notes(week 8) on exception handling
Class notes(week 8) on exception handling
 
Java unit 11
Java unit 11Java unit 11
Java unit 11
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 

Plus de baabtra.com - No. 1 supplier of quality freshers

Plus de baabtra.com - No. 1 supplier of quality freshers (20)

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 
Baabtra soft skills
Baabtra soft skillsBaabtra soft skills
Baabtra soft skills
 
Cell phone jammer
Cell phone jammerCell phone jammer
Cell phone jammer
 
Apple iwatches
Apple iwatchesApple iwatches
Apple iwatches
 
Driverless car
Driverless carDriverless car
Driverless car
 
Brain computer interface(neethu,bincy,sanooja)
Brain computer interface(neethu,bincy,sanooja)Brain computer interface(neethu,bincy,sanooja)
Brain computer interface(neethu,bincy,sanooja)
 
Chapter 5 : How To Program
Chapter  5 : How To ProgramChapter  5 : How To Program
Chapter 5 : How To Program
 

Exeption handling

  • 1.
  • 2. Disclaimer:This presentation is prepared by trainees of baabtra as a part of mentoring program. This is not official document of baabtra –Mentoring Partner Baabtra-Mentoring Partner is the mentoring division of baabte System Technologies Pvt . Ltd
  • 3. Exception Handling vineethmenon18@gmail.com
  • 4. Exception Handling in Java Types of Errors 1.Compile time All syntax errors identified by java compiler. No class file is created when this occurs. So it is necessary to fix all compile time errors for successful compilation. Egs: Missing of semicolon, use of = instead of == 4
  • 5. Exception Handling in Java 2.Run time Some pgms may not run successfully due to wrong logic or errors like stack overflow. Some of the Common run time errors are: Division by 0 Array index out of bounds Negative array size etc.. 5
  • 6. Exception Handling in Java Exception is a condition caused by a run time error in the program. When the java interpreter identifies an error such as division by 0 it creates an Exception object and throws it Definition: An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. Is defined as a condition that interrupts the normal flow of operation within a program. 6
  • 7. Exception Handling in Java Java allows Exception handling mechanism to handle various exceptional conditions. When an exceptional condition occurs, an exception is said to be thrown. For continuing the program execution, the user should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as Exception handling 7
  • 8. Exception Handling in Java This mechanism consists of : 1. Find the problem(Hit the Exception) 2. Inform that an error has occurred(Throw the Exception) 3. Receive the error Information(Catch the Exception) 4. Take corrective actions(Handle the Exception) 8
  • 9. Exception Handling in Java In Java Exception handling is managed by 5 key words: try catch throw throws finally 9
  • 10. Exception Handling in Java In Java Exception handling is managed by 5 key words: try catch throw throws finally 10
  • 11. Exception Handling in Java Exception Hierarchy Package java.lang Throwable Exception error InterruptedException RuntimeException (checked exception) (unchecked exception) 11
  • 12. Exception Handling in Java  Unchecked exception:  These exception need not be included in an method’s throws list  The compiler does not check to see if a method handles or throws these exception  these are subclasses of RuntimeException  The compiler doesn't force client programmers either to catch the exception or declare it in a throws clause.  Class Error and its subclasses also are unchecked.  Checked exception:  Must be included in an method’s throws list if that method can generate one of those exceptions and does not handle it itself  These exception defined by java.lang 12
  • 13. Exception Handling in Java Java’s unchecked RuntimeException subclasses defined in java.lang Exception Meaning ArithmeticException Arithmetic error, such as divide-by-zero ArrayIndexOutOfBoundsException Array index is out-of-bounds ArrayStoreException Assignment to an array element of an incompatible type ClassCastException Invalid cast EnumConstantNotPresentException An attempt is made to use an undefined enumeration value IllegalArgumentException Illegal argument used to invoke a method IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread IllegalStateException Environment or application is in incorrect state IllegalThreadStateException Requested operation not compatible with current thread state IndexOutOfBoundsException Some type of index is out-of-bounds NegativeArraySizeException Array created with a negative size 13
  • 14. Exception Handling in Java Exception Meaning NullPointerException Invalid use of a null reference NumberFormatException Invalid conversion of a string to a numeric format SecurityException Attempt to violate security StringIndexOutOfBoundsException Attempt to index outside the bounds of a string TypeNotPresentException Type not fount UnsupportedOperationException An unsupported operation was encountered 14
  • 15. Exception Handling in Java Java’s checked Exception defined in java.lang Exception Meaning ClassNotFoundException Class not found CloneNotSupportedException Attempt to clone an object that does not implement the Cloneable interface IllegalAccessException Access to a class is denied InstantiationException Attempt to create an object of an abstract class or interface InterruptedException One thread has been interrupted by another thread NoSuchFieldException A requested field does not exist NoSuchMethodException A requested method does not exist 15
  • 16. Exception Handling in Java class Ex{ public static void main(String args[]){ int a=0; int b=2/a; } } Java.lang.ArithmeticException: / by zero at Ex.main 16
  • 17. Exception Handling in Java try & catch try Block Statement that causes Exception Catch Block Statement that causes Exception 17
  • 18. Exception Handling in Java try{ Statement: } catch(Exception-type e){ statement; } 18
  • 19. Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a; try{ d=0; a=10/d; Once an exception is System.out.println("from try"); thrown , program control }catch(ArithmeticException e) transfers out of the try { block into the catch block. System.out.println("divsn by Zero"); Once the catch statement } is executed pgm control System.out.println("after catch"); continues with the next } line following the entire } try/catch mechanism. 19
  • 20. Exception Handling in Java We can display the description of an Exception in a println statement by simply passing the exception as an argument. catch(ArithmeticException ae){ System.out.println(“Exception:”+ae); } o/p Exception:java.lang.ArithmeticException: /by zero 20
  • 21. Exception Handling in Java Common Throwable methods • getMessage(); All throwable objects can have an associated error message. Calling this message will return the message if one present. • getLocalizedMessage(); gets the localized version of error message. • printStackTrace(); sends the stack trace to the system console. This is a list of method calls that led to the exception condition. It includes line number and file names too. Printing of the stack trace is the default behavior of a runtime exception when u don’t catch it ourselves. 21
  • 22. Exception Handling in Java Multiple catch Statement some cases, more than one exception could be raised by a single piece of code. such cases we can specify two or more catch clauses, each catching a different type of exception. when an exception thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is executed. After 1 catch statement is executed, the others are bypassed and execution continues after the try/catch block. 22
  • 23. Exception Handling in Java class Ex{ public static void main(String args[]){ int d,a,len; try{ len=args.length; a=10/len; int c[]={1}; catch(ArithmeticException e){ c[10]=23; System.out.println("divsn by } Zero"+e); } catch(ArrayIndexOutOfBoundsExcept ion ae){ System.out.println("Array index"+ae); } System.out.println("after catch"); } } 23
  • 24. Exception Handling in Java In multiple catch statement exception subclasses must come before any of their superclasses. Because a catch statement that uses a superclass will catch exception of that type plus any of its subclasses. Thus a subclass would never be reached if it came after its superclass. Further java compiler produces an error unreachable code. 24
  • 25. Exception Handling in Java finally It creates a block of code that will be executed after try/catch block has completed and before the code following try/catch block. It will execute whether or not an exception is thrown finally is useful for: •Closing a file •Closing a result set •Closing the connection established with database This block is optional but when included is placed after the last catch block of a try 25
  • 26. Exception Handling in Java Form: try try block {} catch(exceptiontype e) {} finally finally Catch block {} finally 26
  • 27. • If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. • www.baabtra.com | www.massbaab.com |ww w.baabte.com