SlideShare a Scribd company logo
1 of 35
Exception handling
Introduction
Programming errors are unavoidable, even for
experienced programmers. Have three categories of errors:
syntax errors, runtime errors, and logic errors
 Syntax errors arise because the rules of the language have
   not been followed detected by the compiler.

   Runtime errors occur while the program is running if the
    environment detects an operation that is impossible to
    carry out

   Logic errors occur when the program doesn’t perform
    the way it is intended to
Exception handling

Exception handling deals with runtime errors.
 Runtime errors cause exceptions: events that occur
  during the execution of a program and disrupts the
  normal flow of control.

A program that does not provide code to handle
 exceptions may terminate abnormally, causing serious
 problem
The Basics of Java Exception Handling

   Exception handling
       Method detects error which it cannot deal with
           Throws an exception
       Exception handler
           Code to catch exception and handle it
       Exception only caught if handler exists
           If exception not caught, block terminates
The Basics of Java Exception Handling
   Format
       Enclose code that may have an error in try
        block
       Follow with one or more catch blocks
           Each catch block has an exception handler
       If exception occurs and matches parameter in
        catch block
           Code in catch block executed         try{
       If no exception thrown                     code that may throw
                                                 exceptions
           Exception handling code skipped      }
           Control resumes after catch blocks   catch (ExceptionType ref)
                                                 {
                                                    exception handling
                                                 code
                                                 }
The Basics of Java Exception Handling
   Termination model of exception handling
       throw point
           Place where exception occurred
           Control cannot return to throw point
       Block which threw exception expires
       Possible to give information to exception handler
Javaprovides programmers with the capability to handle runtime errors.
With this capability, referred to as exception handling, so you can develop
robust programs for mission-critical computing.

The following program terminates abnormally because the divisor is 0, which
causes a numerical error. Note there is no code to explicitly to explicitly
handle the exception


public class Test
{
         public static void main(String [] args)
   {
      System.out.println(3/0); // Throws ArithmeticException


    }
}
 To handle the divisor by zero error, use a new
 construct called the try-catch block to enable the
 program to catch the error and continue to
 execute.
public class test1
{
          public static void main(String [] args)
          {
                    try
                    {
                    System.out.println(3/0);
                    }
                    catch (Exception ex)
                    {
                             System.out.println("Error:" + ex.getMessage());
                    }
          System.out.println("Execution continues");
    }
}
Exceptions and Exception Types
Various reasons for runtime error:
   The user enters an invalid input – the program may try to
    open a file that does not exist
   the network connection may hang up
   the program may try to access an out of bound s array
    element

When an exception occurs, however, the program may
 terminate if no handler can be used to deal with it.
Catching Exceptions

try {
  statements; //Statement that may throw
              //exceptions
}
catch (Exception1 ex) {
  handler for exception1
}
catch (Exception2 ex) {
  handler for exception2
}
...
catch (ExceptionN ex) {
  handler for exceptionN
}
If no exceptions arise during the execution
of the try clause,the catch clauses are skipped.
Runtime Errors

 1                                        import java.util.Scanner;
 2
 3                                        public class ExceptionDemo {
 4                                          public static void main(String[] args) {
 5                                            Scanner scanner = new Scanner(System.in);
 6                                            System.out.print("Enter an integer: ");
 7                                            int number = scanner.nextInt();
 8   If an exception occurs on this
 9   line, the rest of the lines in the           // Display the result
     method are skipped and the                   System.out.println(
10
     program is terminated.
11                                                  "The number entered is " + number);
12                                            }
13                                        }
      Terminated.
Catch Runtime Errors
 1                                import java.util.*;
 2
 3                                public class HandleExceptionDemo {
 4                                  public static void main(String[] args) {
 5                                    Scanner scanner = new Scanner(System.in);
 6                                    boolean continueInput = true;
 7
 8                                        do {
 9                                          try {
10                                            System.out.print("Enter an integer: ");
11                                            int number = scanner.nextInt();
12    If an exception occurs on this line,
13    the rest of lines in the try block are   // Display the result
14    skipped and the control is               System.out.println(
15    transferred to the catch block.            "The number entered is " + number);
16
17                                             continueInput = false;
18                                          }
19                                          catch (InputMismatchException ex) {
20                                            System.out.println("Try again. (" +
21                                              "Incorrect input: an integer is required)");
22                                            scanner.nextLine(); // discard input
23                                          }
24                                        } while (continueInput);
25                                    }
13                                }
Exception Classes
System Errors




System errors are thrown by JVM
and represented in the Error class.
The Error class describes internal
system errors. Such errors rarely
occur. If one does, there is little
you can do beyond notifying the
user and trying to terminate the
program gracefully.
Exceptions
Exception describes
errors caused by your
program and external
circumstances. These
errors can be caught and
handled by your program.
Runtime Exceptions




                     RuntimeException is caused by
                     programming errors, such as bad
                     casting, accessing an out-of-bounds
                     array, and numeric errors.
Classifying Java Exceptions
   Unchecked Exceptions                               Checked Exceptions
    It is not required that these types of              Must either be caught by a method or
    exceptions be caught or declared on a               declared in its signature.
    method.                                                Placing exceptions in the method
       Runtime exceptions can be generated by              signature harkens back to a major
        methods or by the JVM itself.                       concern for Goodenough.
       Errors are generated from deep within              This requirement is viewed with
        the JVM, and often indicate a truly fatal           derision in the hardcore C++
        state.                                              community.
       Runtime exceptions are a source of                 A common technique for simplifying
        major controversy!                                  checked exceptions is subsumption.
Keywords for Java Exceptions
   throws
    Describes the exceptions which can be raised by a method.
   throw
    Raises an exception to the first available handler in the call stack, unwinding the
    stack along the way.
   try
    Marks the start of a block associated with a set of exception handlers.
   catch
    If the block enclosed by the try generates an exception of this type, control moves
    here; watch out for implicit subsumption.
   finally
    Always called when the try block concludes, and after any necessary catch handler is
    complete.
Canonical Example
public void foo() {
    try { /* marks the start of a try-catch block */
          int a[] = new int[2];
          a[4] = 1; /* causes a runtime exception due to the index */
    } catch (ArrayIndexOutOfBoundsException e) {


          System.out.println("exception: " + e.getMessage());
          e.printStackTrace();
    }
}


/* This code also compiles, but throws an exception at runtime! It
 * is both less obvious and more common (an off-by-one-error). */
public int[] bar() {
    int a[] = new int[2];
    for (int x = 0; x <= 2; x++) { a[x] = 0; }
    return a;
}
blocks

 try {
   statements;
 }
 catch(TheException ex) {
   handling ex;
 }
 finally {
   finalStatements;
 }
Trace a Program Execution
                           Suppose no exceptions in
                           the statements


try {
  statements;
}
catch(TheException ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution

                           The final block is always
                           executed
try {
  statements;
}
catch(TheException ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution

                           Next statement in the
                           method is executed
try {
  statements;
}
catch(TheException ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution

try {                    Suppose an exception of type
                         Exception1 is thrown in
  statement1;            statement2
  statement2;
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution

try {                    The exception is handled.
  statement1;
  statement2;
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution

try {                    The final block is always
                         executed.
  statement1;
  statement2;
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution

try {                    The next statement in the
                         method is now executed.
  statement1;
  statement2;
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution
try {
  statement1;            statement2 throws an
  statement2;            exception of type Exception2.
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
catch(Exception2 ex) {
  handling ex;
  throw ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution
try {
  statement1;            Handling exception
  statement2;
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
catch(Exception2 ex) {
  handling ex;
  throw ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution
try {
  statement1;            Execute the final block
  statement2;
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
catch(Exception2 ex) {
  handling ex;
  throw ex;
}
finally {
  finalStatements;
}

Next statement;
Trace a Program Execution
try {
  statement1;            Rethrow the exception and
  statement2;            control is transferred to the
                         caller
  statement3;
}
catch(Exception1 ex) {
  handling ex;
}
catch(Exception2 ex) {
  handling ex;
  throw ex;
}
finally {
  finalStatements;
}

Next statement;
Cautions When Using Exceptions

   Exception handling separates error-handling code from
    normal programming tasks, thus making programs easier to
    read and to modify. Be aware, however, that exception
    handling usually requires more time and resources because
    it requires instantiating a new exception object, rolling
    back the call stack, and propagating the errors to the
    calling methods.
When to Throw Exceptions

   An exception occurs in a method. If you want the
    exception to be processed by its caller, you should create
    an exception object and throw it. If you can handle the
    exception in the method where it occurs, there is no need
    to throw it.
When to Use Exceptions

When should you use the try-catch block in the code?
You should use it to deal with unexpected error
conditions. Do not use it to deal with simple, expected
situations. For example, the following code
try {
    System.out.println(refVar.toString());
}
catch (NullPointerException ex) {
    System.out.println("refVar is null");
}
When to Use Exceptions

is better to be replaced by

if (refVar != null)
  System.out.println(refVar.toString());
else
  System.out.println("refVar is null");

More Related Content

What's hot

Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaAmbigaMurugesan
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptionssaman Iftikhar
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javagopalrajput11
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templatesfarhan amjad
 
Exception handling
Exception handlingException handling
Exception handlingzindadili
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overviewBharath K
 
Csphtp1 11
Csphtp1 11Csphtp1 11
Csphtp1 11HUST
 
Exceptions in Java
Exceptions in JavaExceptions in Java
Exceptions in JavaVadym Lotar
 
Java Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsJava Pitfalls and Good-to-Knows
Java Pitfalls and Good-to-KnowsMiquel Martin
 
Exception handling
Exception handlingException handling
Exception handlingpooja kumari
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling sharqiyem
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ ConstructorSomenath Mukhopadhyay
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++Deepak Tathe
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handlingAlpesh Oza
 

What's hot (19)

Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Interface andexceptions
Interface andexceptionsInterface andexceptions
Interface andexceptions
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in java
 
Exception handling
Exception handlingException handling
Exception handling
 
Exception handling and templates
Exception handling and templatesException handling and templates
Exception handling and templates
 
Exception handling
Exception handlingException handling
Exception handling
 
Exceptions overview
Exceptions overviewExceptions overview
Exceptions overview
 
Csphtp1 11
Csphtp1 11Csphtp1 11
Csphtp1 11
 
Exception handling
Exception handlingException handling
Exception handling
 
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
Exception handlingException handling
Exception handling
 
C# Exceptions Handling
C# Exceptions Handling C# Exceptions Handling
C# Exceptions Handling
 
Exception Handling in the C++ Constructor
Exception Handling in the C++ ConstructorException Handling in the C++ Constructor
Exception Handling in the C++ Constructor
 
Exception Handling in C++
Exception Handling in C++Exception Handling in C++
Exception Handling in C++
 
Chap12
Chap12Chap12
Chap12
 
Exception handling
Exception handlingException handling
Exception handling
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Week7 exception handling
Week7 exception handlingWeek7 exception handling
Week7 exception handling
 

Similar to Comp102 lec 10

Java exception handling
Java exception handlingJava exception handling
Java exception handlingBHUVIJAYAVELU
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024nehakumari0xf
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024kashyapneha2809
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJAYAPRIYAR7
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javapooja kumari
 
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
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .happycocoman
 
Exception handling in java
Exception handling in javaException handling in java
Exception handling in javaARAFAT ISLAM
 
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
 
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
 
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
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handlingteach4uin
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxVeerannaKotagi1
 

Similar to Comp102 lec 10 (20)

java exception.pptx
java exception.pptxjava exception.pptx
java exception.pptx
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024Java-Exception Handling Presentation. 2024
Java-Exception Handling Presentation. 2024
 
Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024Exception Handling In Java Presentation. 2024
Exception Handling In Java Presentation. 2024
 
JP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.pptJP ASSIGNMENT SERIES PPT.ppt
JP ASSIGNMENT SERIES PPT.ppt
 
UNIT 2.pptx
UNIT 2.pptxUNIT 2.pptx
UNIT 2.pptx
 
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
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
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
 
Exception_Handling.pptx
Exception_Handling.pptxException_Handling.pptx
Exception_Handling.pptx
 
8.Exception handling latest(MB).ppt .
8.Exception handling latest(MB).ppt      .8.Exception handling latest(MB).ppt      .
8.Exception handling latest(MB).ppt .
 
Exception handling in java
Exception handling in javaException handling in java
Exception 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
 
Exception handling
Exception handlingException handling
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
 
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
 
L14 exception handling
L14 exception handlingL14 exception handling
L14 exception handling
 
MODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docxMODULE5_EXCEPTION HANDLING.docx
MODULE5_EXCEPTION HANDLING.docx
 
Exception handling
Exception handlingException handling
Exception handling
 

More from Fraz Bakhsh

More from Fraz Bakhsh (10)

Comp102 lec 9
Comp102   lec 9Comp102   lec 9
Comp102 lec 9
 
Comp102 lec 8
Comp102   lec 8Comp102   lec 8
Comp102 lec 8
 
Comp102 lec 7
Comp102   lec 7Comp102   lec 7
Comp102 lec 7
 
Comp102 lec 6
Comp102   lec 6Comp102   lec 6
Comp102 lec 6
 
Comp102 lec 5.1
Comp102   lec 5.1Comp102   lec 5.1
Comp102 lec 5.1
 
Comp102 lec 5.0
Comp102   lec 5.0Comp102   lec 5.0
Comp102 lec 5.0
 
Comp102 lec 4
Comp102   lec 4Comp102   lec 4
Comp102 lec 4
 
Comp102 lec 3
Comp102   lec 3Comp102   lec 3
Comp102 lec 3
 
Comp102 lec 1
Comp102   lec 1Comp102   lec 1
Comp102 lec 1
 
Comp102 lec 11
Comp102   lec 11Comp102   lec 11
Comp102 lec 11
 

Recently uploaded

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
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
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
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
 

Recently uploaded (20)

Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
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
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
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
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"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
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 

Comp102 lec 10

  • 2. Introduction Programming errors are unavoidable, even for experienced programmers. Have three categories of errors: syntax errors, runtime errors, and logic errors  Syntax errors arise because the rules of the language have not been followed detected by the compiler.  Runtime errors occur while the program is running if the environment detects an operation that is impossible to carry out  Logic errors occur when the program doesn’t perform the way it is intended to
  • 3. Exception handling Exception handling deals with runtime errors.  Runtime errors cause exceptions: events that occur during the execution of a program and disrupts the normal flow of control. A program that does not provide code to handle exceptions may terminate abnormally, causing serious problem
  • 4. The Basics of Java Exception Handling  Exception handling  Method detects error which it cannot deal with  Throws an exception  Exception handler  Code to catch exception and handle it  Exception only caught if handler exists  If exception not caught, block terminates
  • 5. The Basics of Java Exception Handling  Format  Enclose code that may have an error in try block  Follow with one or more catch blocks  Each catch block has an exception handler  If exception occurs and matches parameter in catch block  Code in catch block executed try{  If no exception thrown code that may throw exceptions  Exception handling code skipped }  Control resumes after catch blocks catch (ExceptionType ref) { exception handling code }
  • 6. The Basics of Java Exception Handling  Termination model of exception handling  throw point  Place where exception occurred  Control cannot return to throw point  Block which threw exception expires  Possible to give information to exception handler
  • 7. Javaprovides programmers with the capability to handle runtime errors. With this capability, referred to as exception handling, so you can develop robust programs for mission-critical computing. The following program terminates abnormally because the divisor is 0, which causes a numerical error. Note there is no code to explicitly to explicitly handle the exception public class Test { public static void main(String [] args) { System.out.println(3/0); // Throws ArithmeticException } }
  • 8.  To handle the divisor by zero error, use a new construct called the try-catch block to enable the program to catch the error and continue to execute. public class test1 { public static void main(String [] args) { try { System.out.println(3/0); } catch (Exception ex) { System.out.println("Error:" + ex.getMessage()); } System.out.println("Execution continues"); } }
  • 9. Exceptions and Exception Types Various reasons for runtime error:  The user enters an invalid input – the program may try to open a file that does not exist  the network connection may hang up  the program may try to access an out of bound s array element When an exception occurs, however, the program may terminate if no handler can be used to deal with it.
  • 10. Catching Exceptions try { statements; //Statement that may throw //exceptions } catch (Exception1 ex) { handler for exception1 } catch (Exception2 ex) { handler for exception2 } ... catch (ExceptionN ex) { handler for exceptionN } If no exceptions arise during the execution of the try clause,the catch clauses are skipped.
  • 11. Runtime Errors 1 import java.util.Scanner; 2 3 public class ExceptionDemo { 4 public static void main(String[] args) { 5 Scanner scanner = new Scanner(System.in); 6 System.out.print("Enter an integer: "); 7 int number = scanner.nextInt(); 8 If an exception occurs on this 9 line, the rest of the lines in the // Display the result method are skipped and the System.out.println( 10 program is terminated. 11 "The number entered is " + number); 12 } 13 } Terminated.
  • 12. Catch Runtime Errors 1 import java.util.*; 2 3 public class HandleExceptionDemo { 4 public static void main(String[] args) { 5 Scanner scanner = new Scanner(System.in); 6 boolean continueInput = true; 7 8 do { 9 try { 10 System.out.print("Enter an integer: "); 11 int number = scanner.nextInt(); 12 If an exception occurs on this line, 13 the rest of lines in the try block are // Display the result 14 skipped and the control is System.out.println( 15 transferred to the catch block. "The number entered is " + number); 16 17 continueInput = false; 18 } 19 catch (InputMismatchException ex) { 20 System.out.println("Try again. (" + 21 "Incorrect input: an integer is required)"); 22 scanner.nextLine(); // discard input 23 } 24 } while (continueInput); 25 } 13 }
  • 14. System Errors System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
  • 15. Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
  • 16. Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
  • 17. Classifying Java Exceptions  Unchecked Exceptions  Checked Exceptions It is not required that these types of Must either be caught by a method or exceptions be caught or declared on a declared in its signature. method.  Placing exceptions in the method  Runtime exceptions can be generated by signature harkens back to a major methods or by the JVM itself. concern for Goodenough.  Errors are generated from deep within  This requirement is viewed with the JVM, and often indicate a truly fatal derision in the hardcore C++ state. community.  Runtime exceptions are a source of  A common technique for simplifying major controversy! checked exceptions is subsumption.
  • 18. Keywords for Java Exceptions  throws Describes the exceptions which can be raised by a method.  throw Raises an exception to the first available handler in the call stack, unwinding the stack along the way.  try Marks the start of a block associated with a set of exception handlers.  catch If the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption.  finally Always called when the try block concludes, and after any necessary catch handler is complete.
  • 19. Canonical Example public void foo() { try { /* marks the start of a try-catch block */ int a[] = new int[2]; a[4] = 1; /* causes a runtime exception due to the index */ } catch (ArrayIndexOutOfBoundsException e) { System.out.println("exception: " + e.getMessage()); e.printStackTrace(); } } /* This code also compiles, but throws an exception at runtime! It * is both less obvious and more common (an off-by-one-error). */ public int[] bar() { int a[] = new int[2]; for (int x = 0; x <= 2; x++) { a[x] = 0; } return a; }
  • 20. blocks try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; }
  • 21. Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;
  • 22. Trace a Program Execution The final block is always executed try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;
  • 23. Trace a Program Execution Next statement in the method is executed try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;
  • 24. Trace a Program Execution try { Suppose an exception of type Exception1 is thrown in statement1; statement2 statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;
  • 25. Trace a Program Execution try { The exception is handled. statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;
  • 26. Trace a Program Execution try { The final block is always executed. statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;
  • 27. Trace a Program Execution try { The next statement in the method is now executed. statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;
  • 28. Trace a Program Execution try { statement1; statement2 throws an statement2; exception of type Exception2. statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;
  • 29. Trace a Program Execution try { statement1; Handling exception statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;
  • 30. Trace a Program Execution try { statement1; Execute the final block statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;
  • 31. Trace a Program Execution try { statement1; Rethrow the exception and statement2; control is transferred to the caller statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;
  • 32. Cautions When Using Exceptions  Exception handling separates error-handling code from normal programming tasks, thus making programs easier to read and to modify. Be aware, however, that exception handling usually requires more time and resources because it requires instantiating a new exception object, rolling back the call stack, and propagating the errors to the calling methods.
  • 33. When to Throw Exceptions  An exception occurs in a method. If you want the exception to be processed by its caller, you should create an exception object and throw it. If you can handle the exception in the method where it occurs, there is no need to throw it.
  • 34. When to Use Exceptions When should you use the try-catch block in the code? You should use it to deal with unexpected error conditions. Do not use it to deal with simple, expected situations. For example, the following code try { System.out.println(refVar.toString()); } catch (NullPointerException ex) { System.out.println("refVar is null"); }
  • 35. When to Use Exceptions is better to be replaced by if (refVar != null) System.out.println(refVar.toString()); else System.out.println("refVar is null");

Editor's Notes

  1. Runtime exceptions make it impossible to know what exceptions can be emitted by a method. They also result in incosistent throws decls among developers. Describe subsumption to people: subsumption is often how IOException derivatives are dealt with (subsumption is casting to the base class). The most vituperative debate is between those who believe unchecked exceptions make mechanical testing nearly impossible, and those who believe that checked exceptions impinge on polymorphism by making the exception list part of the method signature (and thereby inheritable).
  2. The top example comes from the JDK documentation.