SlideShare a Scribd company logo
To deal with exceptions




                          1
Objectives

On completion of this period, you would be able to
 know:

• Exception handling mechanism in Java
• How to deal with exceptions




                                                     2
Recap

• In the previous class, you have studied about the
  features and advantages of exceptions
• Advantages are
   • Exception is a built-in class in Java
   • Separation of logic of program for error handling
     section
   • Classification of exceptions possible



                                                     3
Exception Handling Mechanism In Java

• As soon as on exception occurs, the Java runtime
  generates an exception object of the required type

• This is known as creating and throwing exception

• It then checks the method, where the exception is
  generated, for any code to handle the exception

• This method is known as exception handling code
                                                       4
Exception Handling Mechanism In Java
                                                      Contd . . .



• Then, the runtime system checks for each block in
  that method for catch block
• Catch block is known as the exception handler
• If there is no catch block
  • The system checks for catch block, in the calling method of
    the current method




                                                                5
Exception Handling Mechanism In Java
                                                Contd . . .



• The system continuously checks nesting methods
  until main method in checked
• If the current method is main method, then the
  exception message is shown on the error output
• If there is a catch block in any method, the exception
  will be handled




                                                          6
What The Java Run Time Does When An
              Exception Occurs ?     Contd . . .


• The method call sequence is     Method3 without an
                                   exception handler
  shown
• The call sequence starts from   Method2 without an     Method call
  the main method                  exception handler
• main calls Method1
                                   Method1 with an       Method call
• Method1 calls Method2
                                   exception handler
• Method2 calls Method3
                                                         Method call
                                          main


                                  Fig. 43.1 Call stack
Exception Handling Mechanism In Java
                                                                     Contd . . .

•   Here, in Method3          Throws         Method3 without an
    exception occurs          exception       exception handler
                                                                         Looking for
•   Method3 does not                                                     appropriate
    contain the exception                                                handler
                              Forwards       Method2 without an
    handler
                              exception       exception handler
•   Method3 is called by
    method2 which has no                                                Looking for
    exception handler         Catches         Method1 with an           appropriate
                              some            exception handler         handler
•   Method2 is called by      exception
    method1
•   Method1 has exception
                                                     main
    handler
•   In Method1 exception is
    handled
                                          Fig. 43.2 Searching the call stack for
                                          exception handler
How To Deal With Exceptions

• Java exception handling is managed via five
  keywords
  •   try
  •   catch
  •   throw
  •   throws
  •   finally




                                            9
How To Deal With Exceptions Contd...

• Program statements that you want to monitor for
  exceptions are put within a try block
• If an exception occurs within the try block, it is
  thrown
• Your code can catch this exception using catch
  and handle it in some rational manner




                                                       10
How To Deal With Exceptions         Contd..

• System-generated exceptions are automatically
  thrown by the Java run-time system
• To manually throw an exception, use the keyword
  throw




                                                    11
How To Deal With Exceptions           Contd..
• 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 before a
   method returns is put in a finally block
• finally block is useful – for writing clean up code
e.g :
        To close an opened for file
        To close database connection
        To re-initialize variable. etc
                                                        12
Format 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 before try block ends
}


                                                                13
Discussion

• How many try blocks can be there in a method?
• It depends on the type of exceptions we fore-
  see
• How many catch blocks can be there for a try
  block?
• Any number of catch blocks



                                             14
Summary

• In this class we have discussed
  • Exception handling mechanism in java
  • The keywords necessary for handling
    exceptions
     • try, catch, throw, throws and finally




                                               15
Quiz

1. Program statements that you want to monitor for
   exceptions are put within a try block

   A. True
   B. False




                                                     16
Quiz

2. Throw keyword is used to throw an exception,
   manually

   A. True
   B. False




                                                  17
Frequently Asked Questions

1. Explain how to deal with exceptions

2. List the keywords that the java uses for handling
   exception mechanism




                                                       18

More Related Content

What's hot

Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Net
rishisingh190
 
Web technology
Web technology Web technology
Web technology
Siva Priya
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
Nalinee Choudhary
 
JavaScript statements
JavaScript statementsJavaScript statements
JavaScript statements
Victor Verhaagen
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testing
malcolmt
 
Exception handling
Exception handlingException handling
Exception handling
Harry Potter
 

What's hot (7)

Exception Handling in VB.Net
Exception Handling in VB.NetException Handling in VB.Net
Exception Handling in VB.Net
 
Web technology
Web technology Web technology
Web technology
 
Dacj 2-1 b
Dacj 2-1 bDacj 2-1 b
Dacj 2-1 b
 
Nalinee java
Nalinee javaNalinee java
Nalinee java
 
JavaScript statements
JavaScript statementsJavaScript statements
JavaScript statements
 
Bdd and-testing
Bdd and-testingBdd and-testing
Bdd and-testing
 
Exception handling
Exception handlingException handling
Exception handling
 

Viewers also liked

Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39myrajendra
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Codename: Roslyn
Codename: RoslynCodename: Roslyn
Codename: Roslyn
Robert MacLean
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()José Paumard
 
Cross-Platform Mobile Development using Visual Studio and Xamarin
Cross-Platform Mobile Development using Visual Studio and XamarinCross-Platform Mobile Development using Visual Studio and Xamarin
Cross-Platform Mobile Development using Visual Studio and Xamarin
Shravan Kumar Kasagoni
 
Runnable: Discover Everything Through Code
Runnable: Discover Everything Through CodeRunnable: Discover Everything Through Code
Runnable: Discover Everything Through Code
Neil Sood
 

Viewers also liked (6)

Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Codename: Roslyn
Codename: RoslynCodename: Roslyn
Codename: Roslyn
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()
 
Cross-Platform Mobile Development using Visual Studio and Xamarin
Cross-Platform Mobile Development using Visual Studio and XamarinCross-Platform Mobile Development using Visual Studio and Xamarin
Cross-Platform Mobile Development using Visual Studio and Xamarin
 
Runnable: Discover Everything Through Code
Runnable: Discover Everything Through CodeRunnable: Discover Everything Through Code
Runnable: Discover Everything Through Code
 

Similar to Dealing exception.43

Keywords for exceptions.44
Keywords for exceptions.44Keywords for exceptions.44
Keywords for exceptions.44
myrajendra
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
ARUNPRANESHS
 
Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
raksharao
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
raksharao
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
GovindanS3
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
Nuha Noor
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
Ashfaaq Mahroof
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
Adil Mehmoood
 
Exceptions
ExceptionsExceptions
Exceptions
Narayana Swamy
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptionsparthu310
 
8 Exception Handling
8 Exception Handling8 Exception Handling
8 Exception Handling
Deepak Hagadur Bheemaraju
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
promila09
 
exception -ppt.pptx
exception -ppt.pptxexception -ppt.pptx
exception -ppt.pptx
DivyaKS18
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
Elizabeth alexander
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptionsmyrajendra
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
RDeepa9
 

Similar to Dealing exception.43 (20)

Keywords for exceptions.44
Keywords for exceptions.44Keywords for exceptions.44
Keywords for exceptions.44
 
Exception handling in java.pptx
Exception handling in java.pptxException handling in java.pptx
Exception handling in java.pptx
 
Exception handling
Exception handlingException handling
Exception handling
 
Chap2 exception handling
Chap2 exception handlingChap2 exception handling
Chap2 exception handling
 
Java-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handlingJava-Unit 3- Chap2 exception handling
Java-Unit 3- Chap2 exception handling
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Exceptionhandling
ExceptionhandlingExceptionhandling
Exceptionhandling
 
Exception hierarchy
Exception hierarchyException hierarchy
Exception hierarchy
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
16 exception handling - i
16 exception handling - i16 exception handling - i
16 exception handling - i
 
Unit 5
Unit 5Unit 5
Unit 5
 
Exceptions
ExceptionsExceptions
Exceptions
 
Javaexceptions
JavaexceptionsJavaexceptions
Javaexceptions
 
8 Exception Handling
8 Exception Handling8 Exception Handling
8 Exception Handling
 
A36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.pptA36519192_21789_4_2018_Exception Handling.ppt
A36519192_21789_4_2018_Exception Handling.ppt
 
exception -ppt.pptx
exception -ppt.pptxexception -ppt.pptx
exception -ppt.pptx
 
Exception handling in java
Exception handling  in javaException handling  in java
Exception handling in java
 
9 cm604.42
9 cm604.429 cm604.42
9 cm604.42
 
Types of exceptions
Types of exceptionsTypes of exceptions
Types of exceptions
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 

More from myrajendra

Fundamentals
FundamentalsFundamentals
Fundamentals
myrajendra
 
Data type
Data typeData type
Data type
myrajendra
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
myrajendra
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
myrajendra
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
myrajendra
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
myrajendra
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
myrajendra
 
Dao example
Dao exampleDao example
Dao example
myrajendra
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
myrajendra
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to htmlmyrajendra
 
Views
ViewsViews
Views
myrajendra
 

More from myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Recently uploaded

Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
Krisztián Száraz
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
ArianaBusciglio
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
EverAndrsGuerraGuerr
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Thiyagu K
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
thanhdowork
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
RitikBhardwaj56
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
chanes7
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
Thiyagu K
 

Recently uploaded (20)

Advantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO PerspectiveAdvantages and Disadvantages of CMS from an SEO Perspective
Advantages and Disadvantages of CMS from an SEO Perspective
 
Assignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docxAssignment_4_ArianaBusciglio Marvel(1).docx
Assignment_4_ArianaBusciglio Marvel(1).docx
 
The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Thesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.pptThesis Statement for students diagnonsed withADHD.ppt
Thesis Statement for students diagnonsed withADHD.ppt
 
Unit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdfUnit 2- Research Aptitude (UGC NET Paper I).pdf
Unit 2- Research Aptitude (UGC NET Paper I).pdf
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
A Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptxA Survey of Techniques for Maximizing LLM Performance.pptx
A Survey of Techniques for Maximizing LLM Performance.pptx
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptxChapter 4 - Islamic Financial Institutions in Malaysia.pptx
Chapter 4 - Islamic Financial Institutions in Malaysia.pptx
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...The simplified electron and muon model, Oscillating Spacetime: The Foundation...
The simplified electron and muon model, Oscillating Spacetime: The Foundation...
 
S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Digital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion DesignsDigital Artifact 2 - Investigating Pavilion Designs
Digital Artifact 2 - Investigating Pavilion Designs
 
Unit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdfUnit 8 - Information and Communication Technology (Paper I).pdf
Unit 8 - Information and Communication Technology (Paper I).pdf
 

Dealing exception.43

  • 1. To deal with exceptions 1
  • 2. Objectives On completion of this period, you would be able to know: • Exception handling mechanism in Java • How to deal with exceptions 2
  • 3. Recap • In the previous class, you have studied about the features and advantages of exceptions • Advantages are • Exception is a built-in class in Java • Separation of logic of program for error handling section • Classification of exceptions possible 3
  • 4. Exception Handling Mechanism In Java • As soon as on exception occurs, the Java runtime generates an exception object of the required type • This is known as creating and throwing exception • It then checks the method, where the exception is generated, for any code to handle the exception • This method is known as exception handling code 4
  • 5. Exception Handling Mechanism In Java Contd . . . • Then, the runtime system checks for each block in that method for catch block • Catch block is known as the exception handler • If there is no catch block • The system checks for catch block, in the calling method of the current method 5
  • 6. Exception Handling Mechanism In Java Contd . . . • The system continuously checks nesting methods until main method in checked • If the current method is main method, then the exception message is shown on the error output • If there is a catch block in any method, the exception will be handled 6
  • 7. What The Java Run Time Does When An Exception Occurs ? Contd . . . • The method call sequence is Method3 without an exception handler shown • The call sequence starts from Method2 without an Method call the main method exception handler • main calls Method1 Method1 with an Method call • Method1 calls Method2 exception handler • Method2 calls Method3 Method call main Fig. 43.1 Call stack
  • 8. Exception Handling Mechanism In Java Contd . . . • Here, in Method3 Throws Method3 without an exception occurs exception exception handler Looking for • Method3 does not appropriate contain the exception handler Forwards Method2 without an handler exception exception handler • Method3 is called by method2 which has no Looking for exception handler Catches Method1 with an appropriate some exception handler handler • Method2 is called by exception method1 • Method1 has exception main handler • In Method1 exception is handled Fig. 43.2 Searching the call stack for exception handler
  • 9. How To Deal With Exceptions • Java exception handling is managed via five keywords • try • catch • throw • throws • finally 9
  • 10. How To Deal With Exceptions Contd... • Program statements that you want to monitor for exceptions are put within a try block • If an exception occurs within the try block, it is thrown • Your code can catch this exception using catch and handle it in some rational manner 10
  • 11. How To Deal With Exceptions Contd.. • System-generated exceptions are automatically thrown by the Java run-time system • To manually throw an exception, use the keyword throw 11
  • 12. How To Deal With Exceptions Contd.. • 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 before a method returns is put in a finally block • finally block is useful – for writing clean up code e.g : To close an opened for file To close database connection To re-initialize variable. etc 12
  • 13. Format 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 before try block ends } 13
  • 14. Discussion • How many try blocks can be there in a method? • It depends on the type of exceptions we fore- see • How many catch blocks can be there for a try block? • Any number of catch blocks 14
  • 15. Summary • In this class we have discussed • Exception handling mechanism in java • The keywords necessary for handling exceptions • try, catch, throw, throws and finally 15
  • 16. Quiz 1. Program statements that you want to monitor for exceptions are put within a try block A. True B. False 16
  • 17. Quiz 2. Throw keyword is used to throw an exception, manually A. True B. False 17
  • 18. Frequently Asked Questions 1. Explain how to deal with exceptions 2. List the keywords that the java uses for handling exception mechanism 18