Computer Science

Exception Handling

Exception handling is a programming technique used to handle errors and unexpected events that occur during program execution. It involves detecting and responding to these events in a way that prevents the program from crashing or producing incorrect results. Exception handling allows for more robust and reliable software.

Written by Perlego with AI-assistance

11 Key excerpts on "Exception Handling"

  • Book cover image for: An Object-Oriented Approach to Programming Logic and Design
    C H A P T E R 10 Exception Handling In this chapter, you will learn about: Exceptions The limitations of traditional error handling Trying code and catching exceptions Throwing and catching multiple exceptions Using the finally block The advantages of Exception Handling Tracing exceptions through the call stack Creating your own exceptions Copyright 2012 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. Learning About Exceptions An exception is an unexpected or error condition that occurs while a program is running. The programs you write can generate many types of potential exceptions, including the following: l The program issues a command to read a file from a disk, but the file does not exist there. l The program attempts to write data to a disk, but the disk is full. l The program asks for user input, but the user enters invalid data. l The program attempts to divide a value by 0. l The program tries to access an array using a subscript that is too large. l The program calculates a value that exceeds the limit of its variable type. These errors are called exceptions because they are not usual occurrences; they are “ exceptional. ” The object-oriented techniques to manage such errors comprise the group of techniques known as Exception Handling . Sometimes, computer programs generate errors from which the programmer cannot write code to recover. For example, a power failure might interrupt production of your paycheck. Exception Handling does not deal with these kinds of errors; its concern is predictable errors.
  • Book cover image for: Software Essentials
    eBook - PDF

    Software Essentials

    Design and Construction

    Thus, handlers are matched to exception objects. Some han-dlers can be designed to catch (or handle) a wide range of errors. Exceptions automate some error processing. Upon an error condi-tion (exception), the normal flow of execution branches to an exception handler, where error-handling code is executed, and then control flow returns to normal processing. The compiler generates code that sets up the required context changes when standard, expected control flow jumps to exception handlers. As a built-in error-processing language construct, exceptions provide a software design alternative to excessive conditional evaluations. Moreover, exceptions can detect and respond to errors that cannot be uncovered via conditional evaluation. For example, when a library routine receives erro-neous input or enters a state that prevents continued processing, an excep-tion could alert the caller that the request could not be completed normally. Most hardware exceptions are handled “automatically.” Low-level ker-nel code or device drivers translate most interrupts and some processor exceptions into events. Other processor exceptions are translated into software exceptions. For example, code that attempts to access off-limits memory (such as memory allocated to the operating system), generates an exception. Other memory exceptions include stack overflow and failure to satisfy a heap allocation request. If these exceptions are “caught,” the error condition can be “handled” and, ideally, normal control flow resumed. Three statements typically support Exception Handling in modern pro-gramming languages: try, throw, and catch. In many languages, these three specific words are, in fact, reserved words. A try block is the speci-fication of a code block that is to be guarded or enclosed by Exception Handling.
  • Book cover image for: Microsoft Visual C#: An Introduction to Object-Oriented Programming
    You might grumble, “If the program knows what is wrong, why doesn’t it just fix the problem?” In this chapter, you will learn how to handle these unexpected error conditions so your programs can be more user-friendly than those that simply shut down in the face of errors. Understanding Exceptions An exception is any error condition or unexpected behavior in an executing program. Exceptions are caused by errors in program logic or insufficient system resources. The programs you write can generate many types of potential exceptions, including when: • Your program asks for user input, but the user enters invalid data. • The program attempts to divide an integer by zero. • You attempt to access an array with a subscript that is too large or too small. • You calculate a value that is out of range for the answer’s variable type. These errors are called exceptions because presumably they are not usual occurrences; they are “exceptional.” The object-oriented techniques used to manage such errors make up the group of methods known as Exception Handling . If you do not handle an exception, the running program terminates abruptly. Managing exceptions involves an oxymoron; you must expect the unexpected. Errors you discover when compiling a program are not exceptions; they are compiler errors. Only execution-time (also called runtime ) errors are called exceptions. In C#, all exceptions are objects that are instances of the Exception class or one of its derived classes. An exception condition generates an object that encapsulates information about the error. Like all other classes in the C# programming language, the Exception class is a descendant of the Object class. The Exception class has several descendant classes of its own, many with unusual names such as CodeDomSerializerException , SUDSParserException , and SoapException .
  • Book cover image for: Microsoft® Visual C# 2015
    eBook - PDF

    Microsoft® Visual C# 2015

    An Introduction to Object-Oriented Programming

    You might grumble, “If the program knows what is wrong, why doesn’t it just fix the problem?” In this chapter, you will learn how to handle these unexpected error conditions so your programs can be more user-friendly than those that simply shut down in the face of errors. Understanding Exceptions An exception is any error condition or unexpected behavior in an executing program. Exceptions are caused by errors in program logic or insufficient system resources. The programs you write can generate many types of potential exceptions, including when: • Your program asks for user input, but the user enters invalid data. • The program attempts to divide an integer by zero. • You attempt to access an array with a subscript that is too large or too small. • You calculate a value that is too large for the answer’s variable type. These errors are called exceptions because presumably they are not usual occurrences; they are “exceptional.” The object-oriented techniques used to manage such errors make up the group of methods known as Exception Handling . If you do not handle an exception, the running program terminates abruptly. Managing exceptions involves an oxymoron; you must expect the unexpected. Errors you discover when compiling a program are not exceptions; they are compiler errors. Only execution-time (also called runtime ) errors are called exceptions. In C#, all exceptions are objects that are instances of the Exception class or one of its derived classes. An exception condition generates an object that encapsulates information about the error. Like all other classes in the C# programming language, the Exception class is a descendent of the Object class. The Exception class has several descendent classes of its own, many with unusual names such as CodeDomSerializerException , SUDSParserException , and SoapException .
  • Book cover image for: The C++ Workshop
    eBook - ePub

    The C++ Workshop

    A New, Interactive Approach to Learning C++

    • Dale Green, Kurt Guntheroth, Shaun Ross Mitchell(Authors)
    • 2020(Publication Date)
    • Packt Publishing
      (Publisher)
    The program could halt, it could retry a block of code representing some computation to see if the unexpected event goes away, or it could abandon the computation with the unexpected event in it and try to do something else. These handling actions are relatively generic. Each action may be appropriate for many distinct unexpected events.
    C++ Exception Handling is designed for unexpected events—that is, for responding to events that:
    • Occur infrequently and unpredictably
    • Prevent forward progress of the program
    You can, of course, use Exception Handling for expected events, but it's not the right tool for the job. You can also use Exception Handling to return from a function, but it will be slower and harder to explain to colleagues. Exception Handling is not meant for these jobs, any more than a hammer is meant for turning screws. It is possible to pound in screws with a hammer, but it is difficult and inefficient to do so.

    Responding to Unexpected Events

    Unexpected events may be detected anywhere in a program, but they are typically detected in library functions that interact with the operating system and the external world. Calls to these functions are usually found nested many levels deep in the function call stack.
    An unexpected event blocks the forward progress of the program's current computation. The program could choose to halt abruptly when faced with an unexpected event, but if it wants to be able to do anything other than halt (including simply saving work and printing a message), it must abandon the current computation and return to higher-level code that kicks off new computations. It is in this higher-level code that the program can decide whether execution can continue or must be stopped.
    There are two ways this can happen. Traditionally, the function that detected the unexpected event can stop what it's doing, manually clean up any resources it's using, and return an error code to its caller. The caller, in turn, cleans up and returns the error code to its caller. The error code is passed up the calling chain step-by-step, like a bucket brigade, until it arrives at code capable of responding to it, as shown in the following figure:
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    Program Design Including Data Structures

    Exception Handling IN THIS CHAPTER, YOU WILL: 1. Learn what an exception is 2. Learn how to handle exceptions within a program 3. Learn how a try / catch block is used to handle exceptions 4. Learn how to throw an exception 5. Become familiar with C 11 exception classes and how to use them in a program 6. Learn how to create your own exception classes 7. Discover how to throw and rethrow an exception 8. Explore exception-handling techniques 9. Explore stack unwinding 14 CHAPTER © HunThomas/Shutterstock.com Copyright 2018 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. WCN 02-300 1008 | Chapter 14: Exception Handling An exception is an occurrence of an undesirable situation that can be detected during program execution. For example, division by zero is an exception. Similarly, trying to open an input file that does not exist is an exception, as is an array index that goes out of bounds. Until now, we have dealt with certain exceptions by using either an if statement or the assert function. For instance, in Examples 5-3 and 5-4, before dividing sum by counter or count , we checked whether counter or count was nonzero. Similarly, in the Programming Example newString (Chapter 13), we used the assert function to determine whether the array index is within bounds. On the other hand, there were places where we simply ignored the exception. For instance, while determining a substring in a string (Chapter 7), we never checked whether the starting position of the substring was within range. Also, we did not han-dle the array index out-of-bounds exception. However, in all of these cases, if excep-tions occurred during program execution, either we included code to terminate the program or the program terminated with an appropriate error message. For instance, if we opened an input file in the function main and the input file did not exist, we terminated the function main , so the program was terminated.
  • Book cover image for: C++ Programming
    eBook - PDF

    C++ Programming

    From Problem Analysis to Program Design

    Exception Handling IN THIS CHAPTER, YOU WILL: 1. Learn what an exception is 2. Learn how to handle exceptions within a program 3. Learn how a try/catch block is used to handle exceptions 4. Learn how to throw an exception 5. Become familiar with C11 exception classes and how to use them in a program 6. Learn how to create your own exception classes 7. Discover how to throw and rethrow an exception 8. Explore exception-handling techniques 9. Explore stack unwinding 14 CHAPTER © HunThomas/Shutterstock.com Copyright 2016 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s). Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it. 992 | Chapter 14: Exception Handling An exception is an occurrence of an undesirable situation that can be detected during program execution. For example, division by zero is an exception. Similarly, trying to open an input file that does not exist is an exception, as is an array index that goes out of bounds. Until now, we have dealt with certain exceptions by using either an if statement or the assert function. For instance, in Examples 5-3 and 5-4, before dividing sum by counter or count, we checked whether counter or count was nonzero. Similarly, in the Programming Example newString (Chapter 13), we used the assert function to determine whether the array index is within bounds. On the other hand, there were places where we simply ignored the exception. For instance, while determining a substring in a string (Chapter 7), we never checked whether the starting position of the substring was within range. Also, we did not han- dle the array index out-of-bounds exception.
  • Book cover image for: Learn C# Programming
    eBook - ePub

    Learn C# Programming

    A guide to building a solid foundation in C# language for writing efficient programs

    • Marius Bancila, Raffaele Rialdi, Ankit Sharma(Authors)
    • 2020(Publication Date)
    • Packt Publishing
      (Publisher)
    Chapter 14 : Error Handling Historically, managing runtime errors has always been a hard problem to solve because of their complex and different natures, spanning from hardware failures to business logic errors.
    Some of these errors, such as division by zero and null dereferencing , are generated by the CPU itself as an exception, while others are generated at the software level and propagated either as an exception or as an error code, depending on the runtime and programming language.
    The .NET platform has been designed to manage an error condition through an exception strategy, which has the big advantage of dramatically simplifying the handling code. This means that any property or method may throw an exception and communicate the error condition through exception objects.
    Throwing exceptions raises an important question—is the exception part of the contract between the library implementor and its consumer, or is it, rather, an implementation detail?
    In this chapter, we will start analyzing the language syntax needed to participate in the exception model either from a producer or consumer perspective. However, we will also need to go beyond the syntax, analyzing the implications for the developer seeking to debug the causes and the design problems related to both the error-throwing and error-handling sides. The following three sections of this chapter will cover these topics:
    • Errors
    • Exceptions
    • Debugging and monitoring exceptions
    At the end of this chapter, you will be able to catch exceptions from existing libraries, understand whether a method should return a failure code or throw an exception, and create custom exception types whenever it makes sense to.

    Errors

    In software development, the two strategies used to manage errors are error codes and exception handling . The error code model relies exclusively on returning a number whose value represents either success or any possible error. Historically, there has never been a convergence in the way error codes are structured. For example, the Win32 subsystem error codes and the Component Object Model (COM ) define two different sets of error codes in the winerror.h
  • Book cover image for: Creating Components
    eBook - ePub

    Creating Components

    Object Oriented, Concurrent, and Distributed Computing in Java

    This forces the programmer to insert similar code around every file opened to check for a problem. This is referred to as micromanaging an error and ideally should be avoided. Because of the drawbacks of handling errors where they occur and return codes, Java implements error handling using a “try-catch” mechanism, similar to the “try-catch” mechanisms in C++ or Exception blocks in Ada. However, unlike C++ (which, unfortunately, was built on top of C and has a mixed mode for Exception Handling of try-catch and return values), the Exception Handling in Java is consistently built around using these try-catch blocks. And, unlike Ada and C++, Java implements checked exceptions that can validate that a program does in fact handle errors that are likely to occur. The rest of this chapter explains how Exception Handling is implemented in Java. 6.4 Java Exception Handling This section covers the basic mechanism for handling Java exceptions. Generation and handling of exceptions is shown through the use of try-catch blocks. First, simple try-catch blocks and the actions that can be taken in a catch block are shown, then more complicated behaviors of try-catch blocks, such as exception propagation, finally blocks, and re-throwing of exceptions, are discussed. The basic structure of exceptions handling demonstrated in this section is used in subsequent discussion regarding the uses of exceptions in designing components. 6.4.1 Try-Catch Blocks The basic mechanism in Java for handling problems that occur at run time is to try to run a section of code. If it completes normally, then the program proceeds to the next statement after all associated catch blocks. However, if a problem is encountered, the program immediately throws the error. The program then looks at each enclosing try block to see if any mechanism to catch the error has been defined
  • Book cover image for: ABAP to the Future
    No longer available |Learn more
    • Paul Hardy(Author)
    • 2019(Publication Date)
    • SAP PRESS
      (Publisher)
    Section 4.2 ).
  • After the event, when you make an insurance claim, the insurance company will investigate the cause of the blaze. Did you accidently set your house on fire yourself? Did you hire a cook to prepare a banquet, and the cook accidently set the house on fire? In programming terms, the concept of design by contract comes into play here. This means determining if the cause of the error is at the start or end of each routine (Section 4.3 ).
  • Exception Terminology
    This chapter uses five phrases, all with the word exception in them. To make sure you’re not confused, keep the following in mind:
    1. An exception is an unexpected situation. This is a real-world event.
    2. Exception Handling is how a program recognizes and reacts to such an event.
    3. Exception classes are one possible way to implement Exception Handling; as you should have guessed already from the chapter title, they are the focus of this chapter.
    4. Raising an exception is the process of creating an instance of an exception class during Exception Handling.
    5. An exception object is the instance created when raising an exception.

    4.1    Types of Exception Classes

    The first decision you’ll have to make when designing exception classes is what type you need. The type you choose will determine things like whether you handle the error locally or remotely and where you can put handling code. With that in mind, this section talks about each type of exception class and then concludes with a handy little diagram that shows you how to choose the appropriate one (Figure 4.1
  • Book cover image for: Python for Everyone
    eBook - ePub

    Python for Everyone

    Learn and polish your coding skills in Python (English Edition)

    • Saurabh Chandrakar, Dr. Nilesh Bhaskarrao Bahadure(Authors)
    • 2023(Publication Date)
    • BPB Publications
      (Publisher)
    FileNotFoundError and so on. To prevent disruptions, it is highly recommended to handle these exceptions. We need to properly terminate the program if the exceptions are raised during the execution of the program. This can be understood like this.
    Suppose, we are making a Project Initiation Report and are required to submit the same to our HOD by 2 p.m. in the afternoon. By 1:30 p.m., we are modifying the report in our desktop by aligning the data, changing the font, adding some required inputs and outputs and so on. Suddenly, the power is gone and there is no power back up. In this scenario, our entire work goes away in vain since this is an abnormal termination, as well as a non-graceful one. So, to have a graceful termination, Exception Handling is required. No resources should be missing.
    Exception Handling does not mean repairing. It means to have an alternative backup for the current problem. Therefore, defining an alternative way to continue the rest of the program normally, is Exception Handling. Just look at the following 2 statements:
    • S1: You are feeling hungry. You want to eat rice and chapati to satisfy your hunger.
    • S2: You am feeling hungry. You want to eat rice and chapati to satisfy your hunger. If rice and chapati are not cooked, then you will try some snacks. If snacks are also not available, then you will go for biscuits.
    In S2, there are maximum chances of achieving success since there are multiple ways to satisfy the hunger. However, in S1, if there is no rice and chapati, then unfortunately, your hunger will not be unsatisfied. So, there has to be an alternative way to continue rest of the program normally.
    In Python, every exception is an object and the corresponding class is available for every exception type. Python Virtual Machine (PVM ) creates a corresponding exception object whenever an exception occurs. This object checks for handling code. If available, then it will be executed and rest of the program code will be executed normally. If not available, then PVM will terminate the program abnormally and rest of the program code will not be executed. The corresponding exception information will be displayed to the console. This abnormal termination can be handled explicitly using try -except
  • Index pages curate the most relevant extracts from our library of academic textbooks. They’ve been created using an in-house natural language model (NLM), each adding context and meaning to key research topics.