SlideShare una empresa de Scribd logo
1 de 25
Exception Handling


Pre-assessment Questions
    1. Which type of inheritance supports repeating inheritance?
        a. Single level inheritance
        b. Multiple inheritance
        c. Multilevel inheritance
        d. Multipath inheritance

    2. Which keyword is used to define the constants in an interface?
        a. super
        b. public
        c. private
        d. final




 ©NIIT                    Programming in Java               Lesson 1B / Slide 1 of 25
Exception Handling


Pre-assessment Questions (Contd.)
    3. Which concept of object-oriented programming is used in method overriding?
        a. Polymorphism
        b. Abstraction
        c. Encapsulation
        d. Inheritance

    4. What is the return type of the methods declared in an interface?
        a. Default
        b. private
        c. protected
        d. public




 ©NIIT                    Programming in Java               Lesson 1B / Slide 2 of 25
Exception Handling


Pre-assessment Questions (Contd.)
    5.   Which type of inheritance enables you to inherit class data members and
         methods from more than one superclass?
         •   Single level inheritance
         •   Multiple inheritance
         •   Multilevel inheritance
         •   Multipath inheritance




 ©NIIT                    Programming in Java              Lesson 1B / Slide 3 of 25
Exception Handling


Solutions to Pre-assessment
  Questions
    1.   b.    Multiple inheritance
    2.   d.   final
    3.   a.   Polymorphism
    4.   d.   public
    5.   b.   Multiple inheritance




 ©NIIT                       Programming in Java   Lesson 1B / Slide 4 of 25
Exception Handling


Objectives
    •    In this lesson, you will learn to:
           • Identify the various types of exceptions in Java
           • Handle exceptions by using the try, catch, and finally clauses
           • Use the throw statement
           • Implement user-defined exceptions
           • Use assertions in Java




 ©NIIT                     Programming in Java             Lesson 1B / Slide 5 of 25
Exception Handling


Exceptions in Java
    •    An exception can be defined as an abnormal event that occurs during program
         execution and disrupts the normal flow of instructions.
    •    Errors in a Java program are categorized into two groups:
           • Compile-time errors
           • Run Time errors
    •    Concept of Exceptions:
           • The unexpected situations that occur during program execution are:
                • Running out of memory
                • Resource allocation errors
                • Inability to find files
                • Problems in network connectivity




 ©NIIT                     Programming in Java             Lesson 1B / Slide 6 of 25
Exception Handling


Exceptions in Java (Contd.)
    •    Exception Classes


          •   The following figure shows the Exception class heirarchy:




 ©NIIT                       Programming in Java              Lesson 1B / Slide 7 of 25
Exception Handling


Exceptions in Java (Contd.)




 ©NIIT         Programming in Java   Lesson 1B / Slide 8 of 25
Exception Handling


Exceptions in Java (Contd.)
    •    Built-in Exceptions
          • Java consists of the following categories of built-in exceptions:
                 • Checked Exceptions
                 • Unchecked Exceptions




 ©NIIT                       Programming in Java               Lesson 1B / Slide 9 of 25
Exception Handling


Exceptions in Java (Contd.)
    •    The following table lists the various checked exceptions in Java:




                  Exception                                  Cause of Creation

  ClassNotFoundException                           Occurs when the Java run time system
                                                   is unable to find the class referred.

  IllegalAccessException                           Occurs when you want to refer a class
                                                   that is not accessible.
  InstantiationException                           Occurs when you try to create an
                                                   object of an abstract class or interface.

  NoSuchMethodException                            Occurs when you call a method that
                                                   does not exist.


 ©NIIT                       Programming in Java                 Lesson 1B / Slide 10 of 25
Exception Handling


Exceptions in Java (Contd.)
    •    The following table lists the various unchecked exceptions:

               Exception                             Cause of Creation


ArithmeticException                          Occurs when you make an
                                             arithmetic error, such as dividing a
                                             number by zero.

ArrayIndexOutOfBoundsException               Occurs when an attempt is made to
                                             access an array element beyond
                                             the index of the array.

ArrayStoreException                          Occurs when you assign an
                                             element to an array that is not
                                             compatible with the data type of
                                             that array.


 ©NIIT                      Programming in Java              Lesson 1B / Slide 11 of 25
Exception Handling


Exceptions in Java (Contd.)

                 Exception                             Cause of Creation


     ClassCastException                         Occurs when you assign a
                                                reference variable of a class to an
                                                incompatible reference variable of
                                                another class.

     IllegalArgumentException                   Occurs when you pass an
                                                argument of incompatible data
                                                type to a method.

     NegativeArraySizeException                 Occurs when you create an array
                                                with negative size.



 ©NIIT                    Programming in Java               Lesson 1B / Slide 12 of 25
Exception Handling


Exceptions in Java (Contd.)

                Exception                              Cause of Creation


 NullPointerException                          Occurs when an application tries to
                                               use an object without allocating
                                               memory to it or calls a method of a
                                               null object.

 NumberFormatException                         Occurs when you want to convert a
                                               string in an incorrect format to a
                                               numeric format.




 ©NIIT                   Programming in Java               Lesson 1B / Slide 13 of 25
Exception Handling


Implementing Exception Handling
    •    You can implement exception-handling in a program by using the following
         keywords:
          • try
          • catch
          • throw
          • throws
          • finally
    •    Using try and catch statements
          • The try block encloses the statements that might raise an exception
               within it and defines the scope of the exception handlers associated
               with it.
          • The catch block is used as an exception-handler. You enclose the
               code that you want to monitor inside a try block to handle a run time
               error.


 ©NIIT                    Programming in Java             Lesson 1B / Slide 14 of 25
Exception Handling


Implementing Exception Handling
(Contd.)
    •    The following syntax shows how to declare the try-catch block:
         try
         {
                   // Statements that cause an exception.
         }
         catch(ExceptionName obj)
         {
                   // Error handling code.
         }
    •    Using multiple catch statements
         • A single try block can have many catch blocks. This is necessary when
              the try block has statements that raise different types of exceptions.

 ©NIIT                    Programming in Java             Lesson 1B / Slide 15 of 25
Exception Handling


Implementing Exception Handling
(Contd.)
       •    The multiple catch blocks generate unreachable code error.
       •    If the first catch block contains the Exception class object then the
            subsequent catch blocks are never executed.
       • The Exception class being the superclass of all the exception classes catches
            various types of exceptions. The Java compiler gives an error stating that the
            subsequent catch blocks have not been reached.
       • This is known as the unreachable code problem.
       • To avoid unreachable code error, the last catch block in multiple catch
            blocks must contain the Exception class object.
•      Using the finally clause
       • The finally block is used to process certain statements, no matter whether
            an exception is raised or not.




    ©NIIT                     Programming in Java              Lesson 1B / Slide 16 of 25
Exception Handling


Implementing Exception Handling
(Contd.)
    •    The following syntax shows how to declare the try-finally
         block:

         try
         {
               // Block of code
         }
         finally
         {
         // Block of code that is always executed irrespective of
             an exception being raised or not.
         }


 ©NIIT                   Programming in Java            Lesson 1B / Slide 17 of 25
Exception Handling


Throwing an Exception
•      Using the throw statement
       • The throw statement causes termination of the normal flow of control of the
            Java code and stops the execution of the subsequent statements if an
            exception is thrown when the throw statement is executed.
       • The throw clause transfers the control to the nearest catch block handling the
            type of exception object throws.
       • The following syntax shows how to declare the throw statement:
                 throw ThrowableObj
•      Using the throws statement
       • The throws statement is used by a method to specify the types of exceptions
            the method throws.
       • If a method is capable of raising an exception that it does not handle, the
            method must specify that the exception has to be handled by the calling
            method.
       • This is done using the throws statement.

    ©NIIT                    Programming in Java            Lesson 1B / Slide 18 of 25
Exception Handling

Implementing User-Defined Exception
 •   The user-defined Exception class also inherits the methods defined in the
     Throwable class.
 •   The following table lists the various methods defined by the Throwable
     class:

                   Methods                                       Description

     String getMessage()                            Returns a description of the
                                                    exception
     String toString()                              Returns a string object containing a
                                                    description of the exception.

     Throwable fillInStackTrace()                   Returns a Throwable object that
                                                    contains a stack trace

     void printStackTrace()                         Prints the stack trace


 ©NIIT                        Programming in Java                  Lesson 1B / Slide 19 of 25
Exception Handling

Demonstration-Exception Handling in
  Java
    •    Problem Statement


         •   System Software Solutions Inc. needs to store the details, such as
             name, age, and ID of three employees of the company. While
             storing the details of the employees, the record of an employee
             was entered twice and hence the record of the third employee
             could not be displayed. Identify the exception that is raised if the
             details of all the employees were stored. Use the try- catch block
             to handle the exception.




 ©NIIT                  Programming in Java            Lesson 1B / Slide 20 of 25
Exception Handling


Demonstration-Exception Handling in
Java (Contd.)
    •    Solution


         •   To solve the above problem, perform the following tasks:
             •    Identify the type of error and the code segment in which
                  the error occurs.
             •    Identify the mechanism of trapping the exception.
             •    Code the application
             •    Compile and execute the application




 ©NIIT                  Programming in Java          Lesson 1B / Slide 21 of 25
Exception Handling


Assertions in Java
    •    Assertions are the checks provided by the Java language to ensure that any
         assumption made at the start of a program is true throughout the program.
    •    Assertions:
         • Assertions are statements in Java that enable you to test the
              assumptions made in a program during program execution.
         • An assertion statement contains a boolean expression that the
              programmer believes to be true at the time the statement is executed.
         • Assertions are used during testing of a program to ensure that the
              specified condition is true.
         • The following syntax shows how to declare an assertion using assert
              statement in Java:
              assert expressionA;
         • The following syntax shows the compilation of the Java program named
              AssertDemo.java that is using assert statement:
              javac -source 1.4 AssertDemo.java

 ©NIIT                    Programming in Java             Lesson 1B / Slide 22 of 25
Exception Handling


Assertions in Java (Contd.)
    •    The syntax   to enable assertion in a specified class with –ea option is: .
         java –ea:    AssertDemo
    •    The syntax   to disable assertion in a specified class with –da option is:
         java –da:    AssertDemo




 ©NIIT                      Programming in Java                Lesson 1B / Slide 23 of 25
Exception Handling

Summary
   In this lesson, you learned:


   •     Errors can be broadly categorized into two groups on the basis of
         whether the compiler is able to handle the error or not, such as compile
         time errors and run time errors.
   •     An exception is a run time error that can be defined as an abnormal
         event that occurs during the execution of a program and disrupts the
         normal flow of instructions.
   •     In Java, the Throwable class is the superclass of all the exception
         classes. It is the class at the top position in the exception class
         hierarchy. The Exception class and the Error class are two direct
         subclasses of the Throwable class.
   •      The built-in exceptions in Java are divided into two types on the basis of
         the conditions where the exception is raised:
         • Checked Exceptions or Compiler-enforced Exceptions
         • Unchecked exceptions or Runtime Exceptions
 ©NIIT                      Programming in Java               Lesson 1B / Slide 24 of 25
Exception Handling

Summary (Contd.)
   •     You can implement exception handling in your program by using the
         following keywords:
         •     try
         •     catch
         •     throw
         •     throws
         • finally
   •     You use multiple catch blocks to throw more than one type of exception.
   •     The finally clause is used to execute the statements that need to be
         executed whether or not an exception has been thrown.
   •     The throw statement causes termination of the normal flow of control of
         the Java code and stops the execution of subsequent statements after
         the throw statement.
   •     The throws clause is used by a method to specify the types of
         exceptions the method throws.
   •     You can create your own exception classes to handle the situations
         specific to an application
 ©NIIT                     Programming in Java             Lesson 1B / Slide 25 of 25

Más contenido relacionado

La actualidad más candente

Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Dealing exception.43
Dealing exception.43Dealing exception.43
Dealing exception.43myrajendra
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter KitMark Papis
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview QestionsArun Vasanth
 
Java class 7
Java class 7Java class 7
Java class 7Edureka!
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfacesİbrahim Kürce
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 

La actualidad más candente (9)

Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Dealing exception.43
Dealing exception.43Dealing exception.43
Dealing exception.43
 
Java Concurrency Starter Kit
Java Concurrency Starter KitJava Concurrency Starter Kit
Java Concurrency Starter Kit
 
Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Java class 7
Java class 7Java class 7
Java class 7
 
Effective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and InterfacesEffective Java - Chapter 4: Classes and Interfaces
Effective Java - Chapter 4: Classes and Interfaces
 
Effective Java
Effective JavaEffective Java
Effective Java
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 

Destacado

Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception HandlingPrabhdeep Singh
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Javaankitgarg_er
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 

Destacado (6)

exception handling
exception handlingexception handling
exception handling
 
Java - Exception Handling
Java - Exception HandlingJava - Exception Handling
Java - Exception Handling
 
Exception Handling Java
Exception Handling JavaException Handling Java
Exception Handling Java
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 

Similar a Dacj 2-1 b (20)

Exeption handling
Exeption handlingExeption handling
Exeption handling
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
Java exception-handling
Java exception-handlingJava exception-handling
Java exception-handling
 
Keywords for exceptions.44
Keywords for exceptions.44Keywords for exceptions.44
Keywords for exceptions.44
 
Vb.net session 12
Vb.net session 12Vb.net session 12
Vb.net session 12
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Chapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdfChapter 5 Exception Handling (1).pdf
Chapter 5 Exception Handling (1).pdf
 
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
CS3391 -OOP -UNIT – III  NOTES FINAL.pdfCS3391 -OOP -UNIT – III  NOTES FINAL.pdf
CS3391 -OOP -UNIT – III NOTES FINAL.pdf
 
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
 
Java - Exception Handling Concepts
Java - Exception Handling ConceptsJava - Exception Handling Concepts
Java - Exception Handling Concepts
 
Java programming-Event Handling
Java programming-Event HandlingJava programming-Event Handling
Java programming-Event Handling
 
Exception handling in .net
Exception handling in .netException handling in .net
Exception handling in .net
 
Exception handling in ASP .NET
Exception handling in ASP .NETException handling in ASP .NET
Exception handling in ASP .NET
 
exception handling in java.ppt
exception handling in java.pptexception handling in java.ppt
exception handling in java.ppt
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
UNIT III 2021R.pptx
UNIT III 2021R.pptxUNIT III 2021R.pptx
UNIT III 2021R.pptx
 
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
 
Sample
SampleSample
Sample
 

Más de Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Último

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Último (20)

How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

Dacj 2-1 b

  • 1. Exception Handling Pre-assessment Questions 1. Which type of inheritance supports repeating inheritance? a. Single level inheritance b. Multiple inheritance c. Multilevel inheritance d. Multipath inheritance 2. Which keyword is used to define the constants in an interface? a. super b. public c. private d. final ©NIIT Programming in Java Lesson 1B / Slide 1 of 25
  • 2. Exception Handling Pre-assessment Questions (Contd.) 3. Which concept of object-oriented programming is used in method overriding? a. Polymorphism b. Abstraction c. Encapsulation d. Inheritance 4. What is the return type of the methods declared in an interface? a. Default b. private c. protected d. public ©NIIT Programming in Java Lesson 1B / Slide 2 of 25
  • 3. Exception Handling Pre-assessment Questions (Contd.) 5. Which type of inheritance enables you to inherit class data members and methods from more than one superclass? • Single level inheritance • Multiple inheritance • Multilevel inheritance • Multipath inheritance ©NIIT Programming in Java Lesson 1B / Slide 3 of 25
  • 4. Exception Handling Solutions to Pre-assessment Questions 1. b. Multiple inheritance 2. d. final 3. a. Polymorphism 4. d. public 5. b. Multiple inheritance ©NIIT Programming in Java Lesson 1B / Slide 4 of 25
  • 5. Exception Handling Objectives • In this lesson, you will learn to: • Identify the various types of exceptions in Java • Handle exceptions by using the try, catch, and finally clauses • Use the throw statement • Implement user-defined exceptions • Use assertions in Java ©NIIT Programming in Java Lesson 1B / Slide 5 of 25
  • 6. Exception Handling Exceptions in Java • An exception can be defined as an abnormal event that occurs during program execution and disrupts the normal flow of instructions. • Errors in a Java program are categorized into two groups: • Compile-time errors • Run Time errors • Concept of Exceptions: • The unexpected situations that occur during program execution are: • Running out of memory • Resource allocation errors • Inability to find files • Problems in network connectivity ©NIIT Programming in Java Lesson 1B / Slide 6 of 25
  • 7. Exception Handling Exceptions in Java (Contd.) • Exception Classes • The following figure shows the Exception class heirarchy: ©NIIT Programming in Java Lesson 1B / Slide 7 of 25
  • 8. Exception Handling Exceptions in Java (Contd.) ©NIIT Programming in Java Lesson 1B / Slide 8 of 25
  • 9. Exception Handling Exceptions in Java (Contd.) • Built-in Exceptions • Java consists of the following categories of built-in exceptions: • Checked Exceptions • Unchecked Exceptions ©NIIT Programming in Java Lesson 1B / Slide 9 of 25
  • 10. Exception Handling Exceptions in Java (Contd.) • The following table lists the various checked exceptions in Java: Exception Cause of Creation ClassNotFoundException Occurs when the Java run time system is unable to find the class referred. IllegalAccessException Occurs when you want to refer a class that is not accessible. InstantiationException Occurs when you try to create an object of an abstract class or interface. NoSuchMethodException Occurs when you call a method that does not exist. ©NIIT Programming in Java Lesson 1B / Slide 10 of 25
  • 11. Exception Handling Exceptions in Java (Contd.) • The following table lists the various unchecked exceptions: Exception Cause of Creation ArithmeticException Occurs when you make an arithmetic error, such as dividing a number by zero. ArrayIndexOutOfBoundsException Occurs when an attempt is made to access an array element beyond the index of the array. ArrayStoreException Occurs when you assign an element to an array that is not compatible with the data type of that array. ©NIIT Programming in Java Lesson 1B / Slide 11 of 25
  • 12. Exception Handling Exceptions in Java (Contd.) Exception Cause of Creation ClassCastException Occurs when you assign a reference variable of a class to an incompatible reference variable of another class. IllegalArgumentException Occurs when you pass an argument of incompatible data type to a method. NegativeArraySizeException Occurs when you create an array with negative size. ©NIIT Programming in Java Lesson 1B / Slide 12 of 25
  • 13. Exception Handling Exceptions in Java (Contd.) Exception Cause of Creation NullPointerException Occurs when an application tries to use an object without allocating memory to it or calls a method of a null object. NumberFormatException Occurs when you want to convert a string in an incorrect format to a numeric format. ©NIIT Programming in Java Lesson 1B / Slide 13 of 25
  • 14. Exception Handling Implementing Exception Handling • You can implement exception-handling in a program by using the following keywords: • try • catch • throw • throws • finally • Using try and catch statements • The try block encloses the statements that might raise an exception within it and defines the scope of the exception handlers associated with it. • The catch block is used as an exception-handler. You enclose the code that you want to monitor inside a try block to handle a run time error. ©NIIT Programming in Java Lesson 1B / Slide 14 of 25
  • 15. Exception Handling Implementing Exception Handling (Contd.) • The following syntax shows how to declare the try-catch block: try { // Statements that cause an exception. } catch(ExceptionName obj) { // Error handling code. } • Using multiple catch statements • A single try block can have many catch blocks. This is necessary when the try block has statements that raise different types of exceptions. ©NIIT Programming in Java Lesson 1B / Slide 15 of 25
  • 16. Exception Handling Implementing Exception Handling (Contd.) • The multiple catch blocks generate unreachable code error. • If the first catch block contains the Exception class object then the subsequent catch blocks are never executed. • The Exception class being the superclass of all the exception classes catches various types of exceptions. The Java compiler gives an error stating that the subsequent catch blocks have not been reached. • This is known as the unreachable code problem. • To avoid unreachable code error, the last catch block in multiple catch blocks must contain the Exception class object. • Using the finally clause • The finally block is used to process certain statements, no matter whether an exception is raised or not. ©NIIT Programming in Java Lesson 1B / Slide 16 of 25
  • 17. Exception Handling Implementing Exception Handling (Contd.) • The following syntax shows how to declare the try-finally block: try { // Block of code } finally { // Block of code that is always executed irrespective of an exception being raised or not. } ©NIIT Programming in Java Lesson 1B / Slide 17 of 25
  • 18. Exception Handling Throwing an Exception • Using the throw statement • The throw statement causes termination of the normal flow of control of the Java code and stops the execution of the subsequent statements if an exception is thrown when the throw statement is executed. • The throw clause transfers the control to the nearest catch block handling the type of exception object throws. • The following syntax shows how to declare the throw statement: throw ThrowableObj • Using the throws statement • The throws statement is used by a method to specify the types of exceptions the method throws. • If a method is capable of raising an exception that it does not handle, the method must specify that the exception has to be handled by the calling method. • This is done using the throws statement. ©NIIT Programming in Java Lesson 1B / Slide 18 of 25
  • 19. Exception Handling Implementing User-Defined Exception • The user-defined Exception class also inherits the methods defined in the Throwable class. • The following table lists the various methods defined by the Throwable class: Methods Description String getMessage() Returns a description of the exception String toString() Returns a string object containing a description of the exception. Throwable fillInStackTrace() Returns a Throwable object that contains a stack trace void printStackTrace() Prints the stack trace ©NIIT Programming in Java Lesson 1B / Slide 19 of 25
  • 20. Exception Handling Demonstration-Exception Handling in Java • Problem Statement • System Software Solutions Inc. needs to store the details, such as name, age, and ID of three employees of the company. While storing the details of the employees, the record of an employee was entered twice and hence the record of the third employee could not be displayed. Identify the exception that is raised if the details of all the employees were stored. Use the try- catch block to handle the exception. ©NIIT Programming in Java Lesson 1B / Slide 20 of 25
  • 21. Exception Handling Demonstration-Exception Handling in Java (Contd.) • Solution • To solve the above problem, perform the following tasks: • Identify the type of error and the code segment in which the error occurs. • Identify the mechanism of trapping the exception. • Code the application • Compile and execute the application ©NIIT Programming in Java Lesson 1B / Slide 21 of 25
  • 22. Exception Handling Assertions in Java • Assertions are the checks provided by the Java language to ensure that any assumption made at the start of a program is true throughout the program. • Assertions: • Assertions are statements in Java that enable you to test the assumptions made in a program during program execution. • An assertion statement contains a boolean expression that the programmer believes to be true at the time the statement is executed. • Assertions are used during testing of a program to ensure that the specified condition is true. • The following syntax shows how to declare an assertion using assert statement in Java: assert expressionA; • The following syntax shows the compilation of the Java program named AssertDemo.java that is using assert statement: javac -source 1.4 AssertDemo.java ©NIIT Programming in Java Lesson 1B / Slide 22 of 25
  • 23. Exception Handling Assertions in Java (Contd.) • The syntax to enable assertion in a specified class with –ea option is: . java –ea: AssertDemo • The syntax to disable assertion in a specified class with –da option is: java –da: AssertDemo ©NIIT Programming in Java Lesson 1B / Slide 23 of 25
  • 24. Exception Handling Summary In this lesson, you learned: • Errors can be broadly categorized into two groups on the basis of whether the compiler is able to handle the error or not, such as compile time errors and run time errors. • An exception is a run time error that can be defined as an abnormal event that occurs during the execution of a program and disrupts the normal flow of instructions. • In Java, the Throwable class is the superclass of all the exception classes. It is the class at the top position in the exception class hierarchy. The Exception class and the Error class are two direct subclasses of the Throwable class. • The built-in exceptions in Java are divided into two types on the basis of the conditions where the exception is raised: • Checked Exceptions or Compiler-enforced Exceptions • Unchecked exceptions or Runtime Exceptions ©NIIT Programming in Java Lesson 1B / Slide 24 of 25
  • 25. Exception Handling Summary (Contd.) • You can implement exception handling in your program by using the following keywords: • try • catch • throw • throws • finally • You use multiple catch blocks to throw more than one type of exception. • The finally clause is used to execute the statements that need to be executed whether or not an exception has been thrown. • The throw statement causes termination of the normal flow of control of the Java code and stops the execution of subsequent statements after the throw statement. • The throws clause is used by a method to specify the types of exceptions the method throws. • You can create your own exception classes to handle the situations specific to an application ©NIIT Programming in Java Lesson 1B / Slide 25 of 25