100% found this document useful (3 votes)
48 views65 pages

(FREE PDF Sample) Exception Handling: Fundamentals and Programming (SpringerBriefs in Computer Science) 1st Edition Pedro Mejia Alvarez Ebooks

Mejia

Uploaded by

risergreamuu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
48 views65 pages

(FREE PDF Sample) Exception Handling: Fundamentals and Programming (SpringerBriefs in Computer Science) 1st Edition Pedro Mejia Alvarez Ebooks

Mejia

Uploaded by

risergreamuu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 65

Download the Full Version of textbook for Fast Typing at textbookfull.

com

Exception Handling: Fundamentals and Programming


(SpringerBriefs in Computer Science) 1st Edition
Pedro Mejia Alvarez

https://textbookfull.com/product/exception-handling-
fundamentals-and-programming-springerbriefs-in-computer-
science-1st-edition-pedro-mejia-alvarez/

OR CLICK BUTTON

DOWNLOAD NOW

Download More textbook Instantly Today - Get Yours Now at textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

The Common Lisp Condition System: Beyond Exception


Handling with Control Flow Mechanisms 1st Edition Micha■
"Phoe" Herda
https://textbookfull.com/product/the-common-lisp-condition-system-
beyond-exception-handling-with-control-flow-mechanisms-1st-edition-
michal-phoe-herda/
textboxfull.com

Power System Fundamentals 1st Edition Pedro Ponce

https://textbookfull.com/product/power-system-fundamentals-1st-
edition-pedro-ponce/

textboxfull.com

Computer Science Theory and Applications 15th


International Computer Science Symposium in Russia CSR
2020 Yekaterinburg Russia June 29 July 3 2020 Proceedings
Henning Fernau
https://textbookfull.com/product/computer-science-theory-and-
applications-15th-international-computer-science-symposium-in-russia-
csr-2020-yekaterinburg-russia-june-29-july-3-2020-proceedings-henning-
fernau/
textboxfull.com

Computer Supported Qualitative Research 1st Edition


António Pedro Costa

https://textbookfull.com/product/computer-supported-qualitative-
research-1st-edition-antonio-pedro-costa/

textboxfull.com
Discovering Computer Science Interdisciplinary Problems
Principles and Python Programming 1st Edition Jessen
Havill
https://textbookfull.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-1st-
edition-jessen-havill/
textboxfull.com

Python Programming An Introduction to Computer Science


John M. Zelle

https://textbookfull.com/product/python-programming-an-introduction-
to-computer-science-john-m-zelle/

textboxfull.com

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming First Edition Jessen
Havill
https://textbookfull.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-first-
edition-jessen-havill/
textboxfull.com

Discovering Computer Science: Interdisciplinary Problems,


Principles, and Python Programming 2nd Edition Jessen
Havill
https://textbookfull.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-2nd-
edition-jessen-havill/
textboxfull.com

Discovering Computer Science Interdisciplinary Problems


Principles and Python Programming 2nd Edition Jessen
Havill
https://textbookfull.com/product/discovering-computer-science-
interdisciplinary-problems-principles-and-python-programming-2nd-
edition-jessen-havill-2/
textboxfull.com
SpringerBriefs in Computer Science
Pedro Mejia Alvarez · Raul E. Gonzalez Torres ·
Susana Ortega Cisneros

Exception Handling
Fundamentals and
Programming
SpringerBriefs in Computer Science
SpringerBriefs present concise summaries of cutting-edge research and practical
applications across a wide spectrum of fields. Featuring compact volumes of 50 to
125 pages, the series covers a range of content from professional to academic.
Typical topics might include:

• A timely report of state-of-the art analytical techniques


• A bridge between new research results, as published in journal articles, and a
contextual literature review
• A snapshot of a hot or emerging topic
• An in-depth case study or clinical example
• A presentation of core concepts that students must understand in order to
make independent contributions

Briefs allow authors to present their ideas and readers to absorb them with
minimal time investment. Briefs will be published as part of Springer’s eBook
collection, with millions of users worldwide. In addition, Briefs will be available
for individual print and electronic purchase. Briefs are characterized by fast, global
electronic dissemination, standard publishing contracts, easy-to-use manuscript
preparation and formatting guidelines, and expedited production schedules. We
aim for publication 8–12 weeks after acceptance. Both solicited and unsolicited
manuscripts are considered for publication in this series.
**Indexing: This series is indexed in Scopus, Ei-Compendex, and zbMATH **
Pedro Mejia Alvarez • Raul E. Gonzalez Torres
Susana Ortega Cisneros

Exception Handling
Fundamentals and Programming
Pedro Mejia Alvarez Raul E. Gonzalez Torres
CINVESTAV-Guadalajara CINVESTAV-Guadalajara
Zapopan, Jalisco, Mexico Zapopan, Jalisco, Mexico

Susana Ortega Cisneros


CINVESTAV-Guadalajara
Zapopan, Jalisco, Mexico

ISSN 2191-5768 ISSN 2191-5776 (electronic)


SpringerBriefs in Computer Science
ISBN 978-3-031-50680-2 ISBN 978-3-031-50681-9 (eBook)
https://doi.org/10.1007/978-3-031-50681-9

© The Editor(s) (if applicable) and The Author(s), under exclusive license to Springer Nature Switzerland
AG 2024
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher,
whether the whole or part of the material is concerned, specifically the rights of translation, reprinting,
reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software, or by
similar or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication
does not imply, even in the absence of a specific statement, that such names are exempt from the relevant
protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this
book are believed to be true and accurate at the date of publication. Neither the publisher nor the
authors or the editors give a warranty, expressed or implied, with respect to the material contained herein
or for any errors or omissions that may have been made. The publisher remains neutral with regard to
jurisdictional claims in published maps and institutional affiliations.

This Springer imprint is published by the registered company Springer Nature Switzerland AG
The registered company address is: Gewerbestrasse 11, 6330 Cham, Switzerland

Paper in this product is recyclable.


Preface

Whether you’re building a simple app or an intricate software system, things can go
wrong. These unexpected events, or "exceptions", can range from trivial matters like
a missing file to severe errors that can crash an entire system. If these exceptions
are not handled, they can lead to unreliable and unpredictable software behavior.
Exception handling is the process of responding to the occurrence of exceptions
– abnormal or exceptional conditions requiring special processing – during the
software’s execution. Exception handling is crucial in producing robust software
that can cope with unexpected situations, ensuring the software is more resilient,
maintainable, and user-friendly.
In this book, we will delve deep into the world of exception handling with examples
written in C++ and Python. Starting with its history and evolution, we will explore
the many facets of exception handling, such as its syntax, semantics, challenges, best
practices, and more. You’ll understand the nuances between syntax and semantic
errors, learn how to employ try-catch blocks effectively, grasp the importance of
logging exceptions, and even delve into advanced exception-handling techniques.
The following chapters will provide you with a comprehensive understanding of
this crucial software development concept:
Chapter 1 provides an introduction, covering the history, various definitions,
and challenges of exception handling. Chapter 2 delves into the basics, offering
insights into the foundational concepts and techniques. Chapter 3 touches upon the
best practices for exception handling, including the differences between errors and
exceptions, the use of assertions, and how to provide meaningful error messages.
Chapter 4 takes a deep dive into advanced exception-handling techniques. Here, we
explore patterns, guard clauses, hierarchical exception handling, and much more.
Finally, chapter 5 focuses on the complexities of exception handling in real-time and
embedded systems.
Whether you are a seasoned developer looking to refine your understanding of
exception handling or a newcomer eager to grasp its essentials, this book offers a clear,
thorough, and practical guide to mastering this crucial area of software development.
As you progress through the chapters, you will acquire the knowledge and skills
needed to handle exceptions effectively, ensuring that your software applications

v
vi Preface

are more robust, reliable, and resilient to unexpected disruptions. Welcome to the
enlightening journey of mastering exception handling!

CINVESTAV-Guadalajara, Mexico Pedro Mejia-Alvarez


CINVESTAV-Guadalajara, Mexico Raul. E. Gonzalez-Torres
CINVESTAV-Guadalajara, Mexico Susana Ortega-Cisneros
Contents

1 Introduction to Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1


1.1 History and Evolution of Exception Handling . . . . . . . . . . . . . . . . . . . 1
1.2 Definition of Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
1.2.1 Examples of Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.2 Exception Objects and Structures . . . . . . . . . . . . . . . . . . . . . . . 5
1.2.3 Checked and Unchecked Exceptions . . . . . . . . . . . . . . . . . . . . 7
1.2.4 Internal and External Exception Handling . . . . . . . . . . . . . . . . 8
1.2.5 Attachment of Handlers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
1.3 Challenges of Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
1.3.1 Preventing Crashes and Unexpected Behavior . . . . . . . . . . . . 12
1.3.2 Improving Robustness and Maintainability . . . . . . . . . . . . . . . 13
1.3.3 Enhancing Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.4 Syntax and Semantic Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4.1 Syntax Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.4.2 Semantic Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
1.5 Design by Contract: A Precursor to Exception Handling . . . . . . . . . . 15
1.5.1 Principles of Design by Contract . . . . . . . . . . . . . . . . . . . . . . . 15
1.5.2 Relationship with Exceptional Situations . . . . . . . . . . . . . . . . . 15

2 Basics of Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17


2.1 Try-Catch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
2.2 The Throw Keyword in Exception Handling . . . . . . . . . . . . . . . . . . . . 19
2.3 Custom Exceptions Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
2.4 Exception Propagation in Exception Handling . . . . . . . . . . . . . . . . . . . 21
2.5 Nested Try-Catch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
2.5.1 Benefits of Nested try-catch blocks . . . . . . . . . . . . . . . . . . . . . 23
2.5.2 Challenges of Nested Try-Catch Blocks . . . . . . . . . . . . . . . . . . 24
2.5.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
2.5.4 Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6 Conditional Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2.6.1 Event-driven Exception Handling . . . . . . . . . . . . . . . . . . . . . . . 26

vii
viii Contents

3 Exception Handling Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29


3.1 Differences between Errors and Exceptions . . . . . . . . . . . . . . . . . . . . . 30
3.2 Errors as Undesired Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2.1 Critical Aspects to Undesired Events . . . . . . . . . . . . . . . . . . . . 31
3.3 Error Codes and Return Values in Exception Handling . . . . . . . . . . . 33
3.3.1 Error Codes in C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
3.3.2 Return Values as Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
3.4 Assertions and Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.1 Assertions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.4.2 Assertions vs. Exception Handling . . . . . . . . . . . . . . . . . . . . . . 35
3.5 Using Specific Exception Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
3.5.1 Examples of Specific Exception Types . . . . . . . . . . . . . . . . . . . 38
3.6 Providing Meaningful Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.6.1 Examples of Meaningful Error Messages . . . . . . . . . . . . . . . . 41
3.7 Logging Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.7.1 Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
3.7.2 Challenges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.7.3 Examples of Logging Exceptions . . . . . . . . . . . . . . . . . . . . . . . 42
3.8 Handling Exceptions at the Appropriate Level . . . . . . . . . . . . . . . . . . . 44
3.9 Implementing Graceful Degradation and Recovery Strategies . . . . . . 46
3.10 Employing Separation of Concerns in Exception Handling . . . . . . . . 46
3.11 Avoiding Empty Catch Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

4 Advanced Exception Handling Techniques . . . . . . . . . . . . . . . . . . . . . . . . 49


4.1 Exception Handling Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.2 Guard Clauses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.2.1 Exception Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
4.2.2 Exception Aggregation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
4.2.3 Exception Shielding Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
4.3 Retry and Backoff Strategies for Exception Handling . . . . . . . . . . . . . 58
4.3.1 Fixed Interval Retry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
4.3.2 Randomized Interval Retry . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
4.3.3 Decorrelated Jitter Backoff . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4.4 Exception Handling in Multi-Threaded Environments . . . . . . . . . . . . 60
4.4.1 Techniques for Exception Handling in Multi-Threaded
Environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
4.4.2 Challenges and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
4.5 Hierarchical Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
4.5.1 Default Exception Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
4.5.2 Customizing the Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.5.3 Testing and Maintaining the Hierarchy . . . . . . . . . . . . . . . . . . 66
4.5.4 Exception Propagation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
4.5.5 Hierarchical Exception Handling in Different Programming
Paradigms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
4.5.6 Benefits and drawbacks of Hierarchical Exception Handling 68
Contents ix

4.6 Clean-Up Actions in Exception Handling . . . . . . . . . . . . . . . . . . . . . . . 70


4.6.1 The Necessity of Clean-Up Actions . . . . . . . . . . . . . . . . . . . . . 70
4.6.2 Clean-Up Techniques in Different Programming Languages . 71
4.6.3 Best Practices for Clean-Up Actions . . . . . . . . . . . . . . . . . . . . 72

5 Exception Handling in Real-Time and Embedded Systems . . . . . . . . . . 73


5.1 Example of Exceptions in Real-Time Systems . . . . . . . . . . . . . . . . . . . 74
5.2 Constraints in Real-Time Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.2.1 Timing Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.2.2 Resource Constraints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.2.3 Predictability and Determinism . . . . . . . . . . . . . . . . . . . . . . . . 76
5.2.4 Reliability and Fault Tolerance . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.3 Types of Timing Exceptions in Real-time Systems . . . . . . . . . . . . . . . 77
5.3.1 Hardware Timing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.3.2 Software Timing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
5.4 Priorities and Deadlines in Exceptions Handling in Real-time
Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
5.4.1 Prioritizing Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.4.2 Deadline Management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
5.5 Interrupts and Exception Handling in C++ . . . . . . . . . . . . . . . . . . . . . . 83
5.5.1 Linking Interrupts and Exceptions . . . . . . . . . . . . . . . . . . . . . . 84
5.5.2 Similarities and diferences of Interrupts and Exceptions . . . . 85
5.5.3 Combining Interrupts and Exceptions . . . . . . . . . . . . . . . . . . . 86
5.6 Methodologies for Exception Handling in Real-Time Systems . . . . . 87
5.6.1 Recovery Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
5.6.2 Checkpoints and Rollbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.6.3 Proactive Monitoring of Exception Handling in Real-Time
Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
5.7 Design Patterns for Exception Handling in Real-Time Systems . . . . . 91
5.7.1 The Error Handler Pattern in Real-Time Systems . . . . . . . . . . 92
5.7.2 State Machine Pattern in Real-Time Systems . . . . . . . . . . . . . 94
5.7.3 Supervisory Control Pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
5.8 Exception Handling in Ada for Real-Time Systems . . . . . . . . . . . . . . . 98
5.8.1 Defined Exception Model in Ada . . . . . . . . . . . . . . . . . . . . . . . 99
5.8.2 Deterministic Exception Propagation in Ada . . . . . . . . . . . . . . 100
5.8.3 Explicit Exception Declarations in Ada . . . . . . . . . . . . . . . . . . 102
5.8.4 Hierarchical and Scoped Handling in Ada . . . . . . . . . . . . . . . . 103
5.8.5 Tasking and Exception Handling in Ada . . . . . . . . . . . . . . . . . 105
5.8.6 Real-time Considerations in Handler Actions . . . . . . . . . . . . . 107

References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Chapter 1
Introduction to Exception Handling

Exception handling is an essential aspect of software development that enables


programmers to manage unexpected events and errors during program execution.
The chapter begins by providing a general overview of the history and evolution
of exception handling. Then we describe key concepts and principles of exception
handling, including the types of exceptions, how they are defined and raised, and the
different approaches to handling them. This section also delineates the definition of
exceptions, that navigate through the architecture of exception objects, distinctions
between checked and unchecked exceptions, and strategies for internal and external
handling. Furthermore, the process of attaching handlers to specific exceptions is
spotlighted, emphasizing its pivotal role in effective exception management. Excep-
tion handling is not just a theoretical construct; its implications are profound and
far-reaching. In the next section, the chapter underscores the paramount importance
of adept exception handling. By averting crashes and unexpected behavior, fostering
robustness and maintainability, and bolstering security, exception handling elevates
software quality, ensuring users experience reliability and trust in their interactions
with systems. Finally, we also delve into the different types of exceptions, including
syntax and semantic errors.
By the end of the chapter, readers will have a solid understanding of the key
concepts and principles of exception handling and the tools and frameworks avail-
able for implementing effective exception handling in their software projects. The
chapter sets the foundation for the rest of the book, which details specific topics and
techniques related to exception handling in software development.

1.1 History and Evolution of Exception Handling


The history of exception handling [67] can be traced back to the early days of
programming, when languages like Assembly and Fortran were the primary means
of coding. As programming languages and paradigms advanced, the need for better
error and exception-handling mechanisms became apparent. This section provides an
extensive overview of the evolution of exception handling throughout the years. In the

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2024 1


P. Mejia Alvarez et al., Exception Handling, SpringerBriefs in Computer Science,
https://doi.org/10.1007/978-3-031-50681-9_1
2 1 Introduction to Exception Handling

1950s and 1960s, assembly language and Fortran were the dominant programming
languages. They relied on fundamental error-checking mechanisms, using simple
branching instructions to handle errors. As a result, programmers have to write
extensive code to handle different types of errors and exceptions, often leading to
less maintainable and more error-prone code.
One of the first programming languages to introduce structured exception han-
dling was PL/I in the 1960s. The language featured condition handling, where specific
conditions could be associated with particular handlers. However, the system still
required manual management of error propagation, making it less flexible and more
error-prone than modern exception-handling systems. The advent of object-oriented
programming languages like C++ and Python played a crucial role in popularizing
the try-catch-finally construct. This construct allowed developers to write more struc-
tured, maintainable code when dealing with exceptions. In addition, the exception-
handling mechanism provided a clear separation of concerns, with specific blocks
of code designated for error handling and recovery.
As programming languages continue to evolve, newer languages have adopted
more advanced and flexible exception-handling constructs. For example, languages
like Python, C#, and Ruby support exception-handling constructs similar to those
found in Java, focusing on making the code more readable and maintainable. Script-
ing languages, such as JavaScript and PHP, also feature their exception-handling
mechanisms. For example, while JavaScript relies on the try-catch-finally
construct, similar to Java and C++, PHP uses try-catch with optional finally blocks.
In conclusion, exception handling has come a long way since the early days of
programming, with each programming paradigm introducing new approaches and
constructs to handle errors and exceptions effectively. Therefore, studying the history
and evolution of exception-handling mechanisms provides valuable insights into the
progress of programming languages and the software development process.

1.2 Definition of Exceptions


An exception can be defined as an unexpected event or condition that occurs during
the execution of a program, leading to abnormal or undesired behavior [31]. These
events or conditions deviate from the expected or regular flow of the program. They
may result in various consequences, such as incorrect outputs, system crashes, or data
corruption. Exception handling is the process of managing and resolving exceptions
to allow the program to continue executing or terminate gracefully without causing
further harm.
Exceptions can arise from various sources, such as:
• Errors in the code or logic of the program
• Invalid user inputs or actions
• Resource limitations or constraints, such as running out of memory or disk space
• Hardware failures or malfunctions
• External factors, such as network interruptions or loss of communication with
remote services
1.2 Definition of Exceptions 3

1.2.1 Examples of Exceptions

In this section, we provide examples of exceptions with their corresponding imple-


mentation in C++, from the sources discussed before:
• Division by zero: This scenario occurs when attempting to divide a number by
zero, which is an undefined mathematical operation. It often results in a runtime
error or exception.

1 # include <iostream >


2 int main () {
3 int numerator = 5;
4 int denominator = 0;
5
6 try {
7 if ( denominator == 0)
8 throw std :: runtime_error (" Division by zero!");
9 int result = numerator / denominator ;
10 } catch (const std :: runtime_error & e) {
11 std :: cerr << " Error : " << e.what () << std :: endl;
12 }
13
14 return 0;
15 }

• Null pointer dereference: This situation arises when trying to access or deref-
erence a null pointer, which points to no valid memory location. It can lead to
crashes, segmentation faults, or other memory-related errors.

1 # include <iostream >


2 int main () {
3 int* ptr = nullptr ;
4

5 try {
6 if (! ptr)
7 throw std :: runtime_error ("Null pointer dereference
!");
8 *ptr = 10;
9 } catch (const std :: runtime_error & e) {
10 std :: cerr << " Error : " << e.what () << std :: endl;
11 }
12

13 return 0;
14 }

• Out-of-bounds array access: This case occurs when accessing an array element
using an index that exceeds the array’s size or falls outside its defined range. It
can cause unpredictable behavior, memory corruption, or program crashes.
4 1 Introduction to Exception Handling

1 # include <iostream >


2 int main () {
3 int arr [5] = {1, 2, 3, 4, 5};
4
5 try {
6 int index = 10; // out -of - bounds
7 if ( index < 0 || index >= sizeof (arr) / sizeof (arr [0])
)
8 throw std :: out_of_range ("Out -of - bounds array
access !");
9 int val = arr[ index ];
10 } catch (const std :: out_of_range & e) {
11 std :: cerr << " Error : " << e.what () << std :: endl;
12 }
13
14 return 0;
15 }

• Memory allocation failure: In scenarios where dynamic memory allocation is


used (e.g., using new in C++), memory allocation can fail due to various reasons
such as insufficient memory or fragmentation. It results in a std::bad_alloc
exception.

1 # include <iostream >


2 # include <new >
3 int main () {
4 try {
5 int* largeArray = new int[std :: numeric_limits <std ::
size_t >:: max () ];
6 delete [] largeArray ;
7 } catch (const std :: bad_alloc & e) {
8 std :: cerr << " Error: " << e.what () << std :: endl;
9 }
10

11 return 0;
12 }

• File not found or inaccessible: This situation occurs when attempting to access
a file that does not exist or is not accessible due to permissions, network issues,
or other reasons. It results in a runtime error or exception.
• Invalid data type conversion or casting: This scenario arises when performing
an invalid data type conversion or casting operation, such as trying to reinterpret a
value of one type as another incompatible type. It can result in undefined behavior,
data corruption, or type-related errors.
These examples illustrate common scenarios where exceptions can occur in pro-
gramming. Exception-handling mechanisms allow developers to catch and handle
these exceptions gracefully, enabling better control over the program’s behavior and
providing error-recovery strategies.
1.2 Definition of Exceptions 5

1 // File not found or inaccessible in C+


2 # include <iostream >
3 # include <fstream >
4 int main () {
5 std :: ifstream file(" non_existent_file .txt");
6

7 try {
8 if (! file. is_open ())
9 throw std :: runtime_error ("File not found or
inaccessible !");
10 } catch ( const std :: runtime_error & e) {
11 std :: cerr << " Error: " << e.what () << std :: endl;
12 }
13

14 return 0;
15 }

1 // Invalid data type conversion or casting in C++


2 # include <iostream >
3 int main () {
4 int num = 5;
5 void* voidPtr = &num;
6

7 try {
8 char* charPtr = reinterpret_cast <char *>( voidPtr );
9 if (! charPtr )
10 throw std :: runtime_error (" Invalid data type
conversion or casting !");
11 } catch ( const std :: runtime_error & e) {
12 std :: cerr << " Error: " << e.what () << std :: endl;
13 }
14
15 return 0;
16 }

1.2.2 Exception Objects and Structures

In most programming languages, exceptions are represented as objects or structures


that carry information about the nature of the exception, the location in the code
where it occurred, and any additional data that may be relevant to diagnosing or
resolving the issue [31]. Exception handlers can use this information to determine
the appropriate course of action, such as displaying a meaningful error message
to the user, logging the error for debugging purposes, or attempting to recover
from the error and resume normal execution. Exception handling mechanisms in
programming languages like C++ and Python provide the ability to throw and catch
exception objects. Exception objects encapsulate information about an exceptional
condition that occurred during the program’s execution. In this section, we will
explore how exception objects and structures are used in C++ and Python.
6 1 Introduction to Exception Handling

1. C++ programming language:


In C++, exceptions are represented by objects that are derived from the base class
std::exception. Developers can create custom exception classes by inheriting
from std::exception or its derived classes. These exception classes can have
additional member variables and methods to provide more information about the
exception. When an exceptional condition occurs in C++, the throw statement is
used to raise an exception object. The exception object is then caught and handled
by try-catch blocks. The catch block specifies the type of exception to catch,
allowing specific handling based on the type of exception.
Here’s an example of using exception objects in C++:

1 # include <iostream >


2 # include <exception >
3 class MyException : public std :: exception {
4 public :
5 const char* what () const throw () {
6 return "My custom exception ";
7 }
8 };
9 int main () {
10 try {
11 throw MyException ();
12 } catch (const std :: exception & ex) {
13 std :: cerr << " Exception caught : " << ex.what () << std
:: endl;
14 }
15

16 return 0;
17 }

2. Python programming language: In Python, exceptions are represented by ob-


jects that are instances of classes derived from the base class Exception. Python
provides a built-in hierarchy of exception classes that cover various exceptional
conditions. Developers can also create custom exception classes by deriving from
Exception or its derived classes. The raise statement is used to raise an excep-
tion in Python, followed by an instance of an exception class. Exception handling
in Python is done using try-except blocks. The except block specifies the type
of exception to catch, allowing for specific handling based on the exception type.
Here’s an example of using exception objects in Python.

1 class MyException ( Exception ):


2 def __str__ (self):
3 return "My custom exception "
4
5 try:
6 raise MyException ()
7 except Exception as ex:
8 print (f" Exception caught : {ex}")

Listing 1.1: Exception Handling in Python


1.2 Definition of Exceptions 7

Exception objects and structures provide a way to encapsulate and convey in-
formation about exceptional conditions in a program. By using exception objects,
developers can give detailed error messages, stack traces, and other relevant infor-
mation that can aid in debugging and handling exceptional situations. The specific
implementation details and syntax may vary across programming languages, but the
concept of using exception objects remains consistent. Understanding how excep-
tions are represented and handled in different languages allows developers to write
robust, error-tolerant code.

1 // Checked exceptions in C++


2 # include <iostream >
3

4 void readFile () {
5 throw std :: runtime_error ("File not found");
6 }
7 int main () {
8 try {
9 readFile ();
10 } catch ( const std :: exception & e) {
11 // Handle the exception
12 }
13
14 return 0;
15 }

Listing 1.2: Checked Exception in C++

1.2.3 Checked and Unchecked Exceptions

Exception handling in programming languages often categorizes exceptions into


two types: checked and unchecked exceptions. In this section, we will explore the
concepts of checked and unchecked exceptions and how they are handled in different
programming languages [75]. Checked exceptions are exceptions that must be
declared or caught at compile-time. Unchecked exceptions, also known as runtime
exceptions, are exceptions that do not need to be declared or caught at compile-time.
In languages like C++ and Python, exceptions are unchecked by default. Developers
have the flexibility to catch and handle exceptions using try-catch or try-except
blocks, but it is not mandatory.
Next, we provide examples of checked exceptions in C++ and Python languages.
1. C++ programming language: In C++, exceptions are generally unchecked, al-
lowing for a more lightweight and flexible error-handling approach. Developers
can choose to catch and handle exceptions as needed, without being burdened
by explicit exception declarations. In C++, you can throw a built-in or custom
exception and catch it using try-catch, as described in the example above.
8 1 Introduction to Exception Handling

2. Python programming language: In Python, all exceptions are unchecked, pro-


viding developers with the freedom to choose how and when to handle exceptions.
The use of try-except blocks allows for targeted exception handling, making it
easier to write concise and readable code. In Python, you can raise a built-in or
custom exception and catch it using try-except, as in the following listing.

1 def divide (a, b):


2 if b == 0:
3 raise ZeroDivisionError (" Division by zero")
4 # Code that performs division
5 try:
6 divide (10 , 0)
7 except ZeroDivisionError as e:
8 # Handle the exception
9 pass

Listing 1.3: Division by cero in Python

1.2.4 Internal and External Exception Handling

The complexity and unpredictability of software systems often lead to unforeseen


situations or errors, known as exceptions. Based on their origin and nature, these
exceptions can be classified as either internal or external [56]. Understanding these
classifications can be crucial in designing robust exception-handling strategies.
• Internal Exception Handling
Internal exceptions are typical errors that occur within the boundary of a system
or a program. These are often a result of logical errors or incorrect data within
the system. Examples of internal exceptions include divide-by-zero errors, null
pointer dereferencing, out-of-bounds array indexing, and overflow errors. Since
these exceptions originate within the system, they can usually be caught and
handled by the system’s own exception-handling mechanisms. This often involves
error logging, displaying an error message, or, in some cases, terminating the
program if the error cannot be recovered.
1. C++ programming language: In C++, the try and catch blocks are used
for internal exception handling. You can throw exceptions using the throw
keyword, and these can be of any type (integers, characters, objects, etc.).

1 try {
2 // Code that might throw an exception
3 } catch ( ExceptionType1 &e1) {
4 // Handle exception of type ExceptionType1
5 } catch ( ExceptionType2 &e2) {
6 // Handle exception of type ExceptionType2
7 }

Listing 1.4: Internal Exceptions in C++


1.2 Definition of Exceptions 9

2. Phyton programming language: As described before, Python uses a similar


try-except construct. Python also provides a plethora of built-in exceptions
like IOError, ValueError, and you can also define custom exceptions by
creating a new class derived from the base Exception class.

1 try:
2 # Code that might raise an exception
3 except ExceptionType1 as e1:
4 # Handle exception of type ExceptionType1
5 except ExceptionType2 as e2:
6 # Handle exception of type ExceptionType2
7 finally :
8 # This block is always executed

Listing 1.5: Internal Exceptions in Python

• External Exception Handling


External exceptions, in contrast, are caused by conditions outside the system.
These include events such as hardware faults, network connectivity issues, miss-
ing files, or incorrect user inputs. External exceptions are often unpredictable
and can occur even if the system’s internal logic is flawless. Handling external
exceptions requires more sophisticated strategies as they often involve interacting
with external systems or users. For instance, a program may need to retry a failed
network operation, prompt the user for valid input, or log hardware faults for
system administrators to handle. External exception handling relates to the mech-
anisms that exist outside of the primary application logic, usually at the system
or framework level, to catch and manage unforeseen errors.
1. Java programming language: Java’s external exception handling is often
managed by the runtime environment or the container in which the application
is running. For instance, in a web application running on a server like Tomcat,
unhandled exceptions can be caught by the container and a proper HTTP re-
sponse can be returned. Java also allows the definition of uncaught exception
handlers globally using Thread.setDefaultUncaughtExceptionHandler
method [60, 61, 80].
2. C++ programming language: C++ doesn’t have an "external" exception han-
dling mechanism per se. However, if an exception isn’t caught, it will propagate
up to previous levels of the call stack. If it reaches main() and still isn’t caught,
the program will terminate. Some operating systems might provide diagnostics
information or logs. To handle such uncaught exceptions, one can utilize the
std::set_terminate function to set a new termination handler [75].
10 1 Introduction to Exception Handling

1.2.5 Attachment of Handlers

Exception handlers can be associated with different parts of a software system,


including: (i) a single statement, (ii) a block of statements, (iii) a function or method,
(iv) an instance of a class, or (v) a class definition [56].
1. Statement Handlers: Statement handlers can be attached to a single statement.
In the following Python code, the ZeroDivisionError is handled right at the
division operation:

1 try:
2 x = 1 / 0
3 except ZeroDivisionError :
4 print ("Error: Division by zero.")

In this example, the handler is attached to the division statement, making it a


statement handler [62].
2. Block Handlers: Block handlers are associated with a block of statements. In
Java, exceptions within a block can be handled using a try/catch block. In this
Java code, the handler is attached to a block of statements, making it a block
handler [32].

1 try {
2 int result1 = 10 / 0;
3 int result2 = result1 + 2;
4 } catch ( ArithmeticException e) {
5 System .out. println (" Error : Division by zero.");
6 }

3. Method Handlers: Method handlers are attached to a specific method. In the


following Python code, the ZeroDivisionError exception is handled within
the divide_numbers method. In this Python code, the handler is attached to the
divide_numbers method, making it a method handler [62].

1 def divide_numbers (a, b):


2 try:
3 result = a / b
4 except ZeroDivisionError :
5 print("Error: Division by zero.")
6 result = None
7 return result
8

9 divide_numbers (1, 0) # This will raise and handle a


ZeroDivisionError .
1.2 Definition of Exceptions 11

4. Object Handlers and Class Handlers


Object handlers are specific to instances of a class. While most popular languages
like Python or Java do not directly support attaching handlers to objects, they
provide ways to define methods that can handle exceptions at the instance level.

1 class MyClass :
2
3 def __init__ (self , value):
4 self. value = value
5 def divide_by (self , divisor ):
6 try:
7 return self. value / divisor
8 except ZeroDivisionError :
9 print("Error in MyClass : Division by zero.")
10 return None
11

12 # Object - level handler


13 obj1 = MyClass (10)
14 result1 = obj1. divide_by (0) # This will raise and handle a
ZeroDivisionError .
15
16 # Class - level handler
17 result2 = MyClass . divide_by (obj1 , 0) # Equivalent to the
previous line.

Similarly, class handlers are attached to a class definition. Mainstream languages


like Python and Java do not directly support attaching handlers to classes. How-
ever, they provide ways to define methods that can handle exceptions at the class
level. In Python, exception handling can be designed at the object and class lev-
els by defining methods that handle exceptions. Consider the example above. In
the above Python code, the divide_by method acts as both an object-level and
class-level handler. If an exception is raised during the division operation, the
method will handle it, and the handling behavior will be the same for all instances
of MyClass. This demonstrates how exception handling can be designed at the
class and object levels in Python, even though the language doesn’t have explicit
support for attaching handlers to classes or objects [62].
In Java, methods within an object or class can be designed to handle exceptions.
Consider the following example below. In this Java code, the divideBy method
acts as an object-level handler. If an ArithmeticException is raised during the
division operation, the method will handle it. The handling behavior will be the
same for all instances of MyClass. This demonstrates how exception handling
can be designed at the object level in Java, even though the language doesn’t
explicitly support attaching handlers to objects [32].
12 1 Introduction to Exception Handling

1 public class MyClass {


2 private int value;
3

4 public MyClass (int value) {


5 this. value = value ;
6 }
7
8 public int divideBy (int divisor ) {
9 try {
10 return value / divisor ;
11 } catch ( ArithmeticException e) {
12 System .out. println ("Error in MyClass : Division by
zero.");
13 return 0;
14 }
15 }
16 }
17
18 // Object -level handler
19 MyClass obj1 = new MyClass (10);
20 int result1 = obj1. divideBy (0); // This will raise and handle
an ArithmeticException .
21

22 // Class - level handler is not applicable in Java as non - static


methods require an object instance .

1.3 Challenges of Exception Handling

Exception handling is a critical aspect of software development that enables pro-


grammers to manage unexpected events and errors that can occur during program
execution [31]. Without proper exception handling, errors and exceptional condi-
tions can cause software applications to crash or behave unpredictably, leading to
lost data, frustrated users, and potential security vulnerabilities. Exception handling
has two main objectives: (1) to detect and report errors that occur during the execu-
tion of a program, and (2) to facilitate the recovery from these errors and continue
the program’s execution [31]. It is crucial to note that not all errors are exceptions,
as exceptions represent a subset of unexpected, abnormal, or otherwise exceptional
errors. The primary challenge of exception handling is to provide a robust system that
is easy to understand, implement, and maintain while minimizing the performance
overhead associated with error detection and recovery.

1.3.1 Preventing Crashes and Unexpected Behavior


One of the primary benefits of exception handling is that it can prevent crashes and
unexpected behavior in software applications [33]. Errors and exceptional conditions
1.3 Challenges of Exception Handling 13

can arise from a wide range of sources, including user input, hardware failures,
network issues, and software bugs. By implementing proper exception handling,
programs can detect and handle these errors in a controlled and graceful manner,
preventing the program from crashing or terminating prematurely. Consider, for
instance, a program that reads data from a file and performs some calculations on the
data. If the file is not found or cannot be read, the program will encounter an error and
fail to execute. However, with proper exception handling, the program can detect the
error and gracefully exit, providing feedback to the user and avoiding any unexpected
behavior. Another example is a program that performs network communication. If
a network connection is lost or interrupted, the program may encounter an error
and terminate. However, with proper exception handling, the program can detect
the error and attempt to reconnect, ensuring that the communication can continue
without any significant impact on the user.

1.3.2 Improving Robustness and Maintainability


Another benefit of proper exception handling is that it can improve the overall
robustness and maintainability of software applications [71]. By implementing a
systematic approach to handling errors and exceptional conditions, programmers
can ensure that their programs are resilient and can withstand a wide range of
scenarios and inputs. For instance, a program that performs network communication
may encounter errors due to network latency, packet loss, or other issues. With
proper exception handling, the program can detect and handle these errors, ensuring
that the communication can continue without any significant impact on the user.
Furthermore, proper exception handling can also enhance the maintainability of
software applications by enabling programmers to isolate and debug errors more
efficiently. By providing detailed error messages and stack traces, exception handling
can help programmers identify the root cause of errors and implement effective fixes.

1.3.3 Enhancing Security


Proper exception handling can also enhance the security of software applications by
preventing malicious inputs or attacks from causing unexpected behavior or exposing
vulnerabilities [33]. By detecting and handling errors and exceptional conditions in
a secure and controlled manner, programs can mitigate the risk of security breaches
and protect sensitive data. For example, a program that performs database queries
may encounter errors due to invalid input or malicious SQL injection attacks. With
proper exception handling, the program can detect and handle these errors, preventing
the injection of malicious code and protecting the integrity and confidentiality of the
database.
14 1 Introduction to Exception Handling

1.4 Syntax and Semantic Errors

In software development, errors and exceptions are common occurrences that can
lead to unexpected program behavior, crashes, and incorrect results. Therefore,
understanding the different types of errors and exceptions is essential for developing
robust and reliable software applications that can handle unexpected events and
gracefully recover from errors.

1.4.1 Syntax Errors

Syntax errors occur when the program’s syntax is incorrect, leading to a compile-
time error. These errors are easy to detect and fix, as they cause the program to fail
to compile. Here’s an example of a syntax error in C programming:

1 # include <stdio .h>


2 int main () {
3 printf ("Hello , World !\n")
4 return 0;
5 }

In this example, the program attempts to print a message to the console but needs
to include a semicolon at the end of the line. This results in a syntax error, which
causes the program to fail to compile.

1.4.2 Semantic Errors

Semantic errors occur when the program’s logic is incorrect [50], leading to unex-
pected or incorrect results. Various factors, such as incorrect calculations, algorithms,
or data types, can cause these errors. Semantic errors can be challenging to detect
and fix, as they may not cause the program to crash or generate an error message.
Here’s an example of a semantic error in Python programming:

1 def divide (a, b):


2 return a / b
3
4 result = divide (10 , 0)
5 print( result )

In this example, the program attempts to divide a number by zero, which is


undefined. The program does not generate an error message but returns an incorrect
result, causing unexpected behavior.
1.5 Design by Contract: A Precursor to Exception Handling 15

1.5 Design by Contract: A Precursor to Exception Handling


Design by Contract (DbC) [54] is a powerful software correctness methodology
introduced by Bertrand Meyer in the 1980s, associated primarily with the Eiffel
programming language. At its core, it emphasizes the mutual obligations and benefits
between two parties — a routine and its caller. This approach can be seen as a
precursor to the concept of exception handling, setting the groundwork for how
software deals with exceptional situations.

1.5.1 Principles of Design by Contract


The main principles of DbC revolve around three primary annotations:
• Preconditions: What must be true before a routine can be executed. It is the
caller’s responsibility to satisfy these conditions.
• Postconditions: What will be true after the routine has been executed, assuming
the preconditions were met. This is the responsibility of the routine itself.
• Invariants: Conditions that must always hold true, irrespective of the routine’s
execution. Typically, invariants relate to the state of an object.
These contract elements ensure that as long as the caller keeps their side of the
"contract" by fulfilling the preconditions, the routine guarantees that it will achieve
the postconditions and maintain the invariants.

1.5.2 Relationship with Exceptional Situations


DbC’s principles lay the foundation for understanding exceptional situations in a
number of ways:
• Violation of Contracts: If a precondition, postcondition, or invariant is violated,
it’s indicative of an exceptional situation. For instance, if a routine expects a
positive integer as an input (precondition) but receives a negative one, it’s a
breach of contract.
• Explicit Expectations: DbC makes the expectations explicit. This clarity often
reduces the number of exceptional situations because potential issues are caught
early in the development phase.
• Failure as a Breach of Contract: Instead of thinking of failures as errors, they’re
seen as contract breaches. This perspective shift changes the way developers
approach problem-solving. If a postcondition isn’t met, it’s not merely a "bug";
it’s a failure of the software to uphold its end of the contract.
• Exception Handling Mechanism: Modern exception handling can be viewed as
an evolution of the DbC principle. When an exception is thrown, it’s essentially
signaling that some part of the "contract" (often an implicit one) has been vio-
lated. Catching and handling that exception allows developers to deal with these
breaches in a controlled manner.
16 1 Introduction to Exception Handling

• Predictable Software Behavior: Both DbC and exception handling aim to make
software behavior more predictable. While DbC does this through clear con-
tracts, exception handling provides mechanisms to deal with unpredicted scenar-
ios gracefully.

Bertrand Meyer’s Design by Contract emphasized the clear delineation of respon-


sibilities in software components. This clarity and explicitness in defining obligations
and benefits set the stage for more advanced exception-handling mechanisms. By
understanding the contractual obligations between different software components,
developers can better anticipate, handle, and recover from exceptional situations,
leading to more robust and resilient software.
Chapter 2
Basics of Exception Handling

As programmers, we embark on the journey of software creation with the aim of


achieving flawless execution. Yet, software, being a construct of human endeavor, is
susceptible to unforeseen challenges. These challenges, if unmitigated, can morph
into frustrating experiences for the end-users. Exception handling, therefore, stands
as a beacon, guiding us to not only anticipate these challenges but also respond to
them with grace and efficacy.
In this chapter, we will uncover the fundamental pillars of exception handling.
We begin with Try-catch blocks, the first line of defense against unpredicted hic-
cups during program execution. Moving on, we’ll delve into the realm of the throw
keyword, an essential tool enabling programmers to raise custom alerts. The next
section is dedicated to the art of crafting Custom Exceptions, allowing for a more
granular level of error classification and response. As we progress in the chapter,
the concept of Exception Propagation comes to the fore, illuminating how excep-
tions ripple through the layers of our code. A deeper dive into the architecture of
exception handling awaits with Nested try-catch blocks. Here, we’ll examine the
manifold benefits and potential pitfalls of stacking our defense mechanisms. A series
of examples, best practices, and a comparative study across various programming
languages will further enrich our understanding. Lastly, we will explore the nuanced
world of Conditional Exception Handling, introducing the reader to a more dynamic
and responsive approach to error management, including the intriguing paradigm of
Event-driven Exception Handling.

2.1 Try-Catch Blocks

Try-catch blocks are a programming construct that enables the handling of exceptions
or errors during the execution of a program. When an error occurs within a try block,
the program flow is directed to the corresponding catch block, where the error can
be managed gracefully, without crashing the entire program. Many programming
languages, such as Java, C++, 𝐶#, Python, and JavaScript, offer built-in support for

© The Author(s), under exclusive license to Springer Nature Switzerland AG 2024 17


P. Mejia Alvarez et al., Exception Handling, SpringerBriefs in Computer Science,
https://doi.org/10.1007/978-3-031-50681-9_2
18 2 Basics of Exception Handling

try-catch blocks. In this section, we will explore the concept of try-catch blocks in
various programming languages.
1. Try-Catch blocks in C++: In C++, try-catch blocks are used to manage ex-
ceptions that may occur during the program execution. The following example
demonstrates a simple try-catch block in C++:

1 # include <iostream >


2 # include <stdexcept >
3

4 int main () {
5 int a = 5, b = 0;
6 int result ;
7
8 try {
9 if (b == 0) {
10 throw std :: runtime_error (" Division by zero.");
11 }
12 result = a / b;
13 std :: cout << " Result : " << result << std :: endl;
14 } catch (const std :: runtime_error & e) {
15 std :: cout << " Error : " << e.what () << std :: endl;
16 }
17

18 return 0;
19 }

In this example, we try to perform a division operation that could potentially


lead to a division-by-zero error. When the exception occurs, the catch block is
executed, and a descriptive error message is printed to the console.
2. Try-Except blocks in python: In Python, try-catch blocks are called try-except
blocks. The following example demonstrates a simple try-except block in Python:

1 numbers = [1, 2, 3]
2

3 try:
4 print ( numbers [3])
5 except IndexError :
6 print ("Error: List index out of range.")

In this example, we again try to access an array element with an invalid index.
When the exception occurs, the except block is executed, and a descriptive error
message is printed to the console.
2.3 Custom Exceptions Handling 19

2.2 The Throw Keyword in Exception Handling

The throw keyword is an essential component of exception handling in many pro-


gramming languages. It allows developers to explicitly raise an exception in the code,
which can then be caught and managed by a suitable exception-handling mechanism.
This section will discuss the purpose and usage of the throw keyword in various pro-
gramming languages.
1. C++: In C++, the throw keyword is used to raise an exception explicitly. Custom
exception classes can be created by inheriting from one of the standard exception
classes in the stdexcept library or from a custom-made base exception class.
The following example shows throwing a built-in exception in C++.

1 # include <stdexcept >


2

3 void checkAge (int age) {


4 if (age < 18) {
5 throw std :: invalid_argument ("Age must be at least 18."
);
6 }
7 }

2. Python: In Python, the raise keyword is used instead of throw to raise an exception
explicitly. Custom exception classes can be created by inheriting from the built-in
Exception class or one of its subclasses.
The following shows raising a built-in exception.

1 def check_age (age):


2 if age < 18:
3 raise ValueError ("Age must be at least 18.")

2.3 Custom Exceptions Handling

In exception handling, custom exceptions can be created to handle specific error


conditions or unusual scenarios that are not covered by the built-in exceptions pro-
vided by the language. Custom exceptions can make error reporting and debugging
more informative and easier to understand. This section will discuss the creation and
usage of custom exceptions in various programming languages.
1. C++: In C++, custom exceptions can be created by inheriting from one of the
standard exception classes in the stdexcept library or by creating a custom
base exception class. A custom exception class can have additional methods or
properties to provide more context or information about the exception.
Random documents with unrelated
content Scribd suggests to you:
Man at very hard outdoor winter
125 180 200 600 650 4592
work
U. S. Army rations 64 106 280 460 540 4896-5032
U. S. Navy rations ... 143 292 557 ... 5545
Football team (old régime) ... 181 292 557 ... 5697
College football team (new) 125 125 125 500 ... 3675

TABLE XII
Rations Varied for Sex and Age

Proteins Carbohydrates
VARIATIONS OF SEX AND AGE Fats Energy in Calories
Low High Low High
Children, two to six 36 70 40 250 325 1520-1956
Children, six to fifteen 50 75 45 325 350 1923-2123
Women with light exercise 50 80 80 300 330 2272
Women at moderate work 60 92 80 400 432 2720
Aged women 50 80 50 270 300 1870
Aged men 50 100 400 300 350 2258

The unit of measurement for the calories of energy is the amount


of heat required to raise the temperature of one kilogram of water
from zero to 1° centigrade or 4° Fahrenheit.
In estimating the number of calories of energy given off by the
different foods, Dr. Hall represents

1 gram of carbohydrates as 4.0 calories


1 ” ” fats ” 9.4 ”
1 ” ” proteins ” 4.0 ”

To determine the relative energy which a food represents, it is


only necessary to multiply the number of grams of protein in that
food by 4, the fat by 9.4, and the carbohydrates by 4, and add the
results.
Thus according to the food required for the average man at light
work given on page 225:

grams
106.80 proteins × 4 = 427.20 calories of energy
of
9.4
57.97 ” ” fat × 544.94 ” ” ”
=
398.84 ” ” carbohydrates × 4 = 1595.36 ” ” ”
2567.51 = the calories of energy
required for the average man at light
work.

TABLE XIII

The following gives a balanced supply for a day according to the


preceding tabulation:
Amount of Food Calories
2 tablespoonfuls fruit with sugar 55
2 eggs 140
1/
2 pound lean meat (protein) 243
1 pound bread 1206
1/
2 pint soup 307
1 tablespoonful cocoa 135
2 potatoes (average size) 100
1/
2 pint of milk 150
2 pats butter (1 cubic inch) 119
2 tablespoonfuls sugar 112
2567

Dr. Chittenden’s experiments would indicate that a man leading a


very active life, and above the average in body weight, can maintain
his body in equilibrium indefinitely with a daily intake of thirty-six to
forty grams of protein, or albuminoid food, with a total fuel value of
1600 calories.
In order to bring oneself to as limited a diet as Professor
Chittenden’s men followed, however, it would be necessary to have
all food weighed so as to be sure of the correct proportions;
otherwise the actual needs would not be supplied and the body
would suffer.
It is a question whether the men with whom he experimented
could have followed so limited a diet for an indefinite period.
As stated, however, authorities differ on the amount of food
required.

Dr. Hall suggests 106 grams of protein


Ranke suggests 100 grams of protein
Hultgren and Landergren suggest 134 grams of protein
Schmidt suggests 105 grams of protein
Forster and Moleschott suggest 130 grams of protein
Atwater suggests 125 grams of protein

A wise provision of Nature enables the body to throw off an


excess of food above its needs without injury, within limitations; but,
as stated, there is no doubt that the average person exceeds these
limits, exhausting the digestive organs and loading the system with
more than it can eliminate; the capacity for mental work becomes
restricted, and the whole system suffers.

From the fact that only from two to four ounces


Mixed Diet of nitrogenous food are required to rebuild daily
versus a tissue waste, it is apparent that this amount can
Vegetarian Diet
readily be supplied from the vegetable kingdom,
since nuts, legumes, and cereals are rich in proteins; yet there is a
question whether a purely vegetable diet is productive of the highest
physical and mental development. Natives of tropical climates live on
vegetables, fruits, and nuts, and it may be purely accidental, or be
due to climatic or other conditions, that these nations have not
made the greatest progress. Neither have the Eskimos, who live
almost entirely on meat, attained the highest development.
The greatest progress and development, both as nations and as
individuals, have been made by inhabitants of temperate climates,
who have lived on a mixed diet of meat, eggs, milk, grains,
vegetables, fruits, and nuts. They have shown more creative force,
which means reserve strength.
The Eskimo has demonstrated, however, that a diet of meat alone
supplies all physical needs; the meat tissue providing growth and
repair and the fat supplying all of the carbonaceous elements. The
fat, as previously stated, yields more heat than starches and sugars,
and Nature provides this heat for climates in which most warmth is
required. This may be the reason why natives of warm climates have
formed the habit of using vegetables and grains for their heat and
energy rather than meat. It is also the natural reason why man in
temperate climates eats more meat in winter than in summer.
An unperverted, natural instinct will always be found to have a
sound physiological basis. For example, if, by reason of some
digestive disturbance, one has become emaciated, all of the fat
having been consumed, and the cause of the disturbance is removed
by an operation or otherwise, one is seized with an almost insatiable
desire for fat, often eating large chunks of the fat of meat or large
quantities of butter or cream at a meal. When obstructions are
removed, Nature makes immediate effort to readjust her forces.
Those who object to eating meat should study carefully to learn if
the proper proportion of protein is supplied with each day’s rations.
The legumes—peas, beans, nuts, and grains—must be supplied.
While the wheat kernel contains twelve per cent. of protein, the
white flour does not contain as large a percentage and it will be
noted by reference to Tables II and III, that the majority of fruits
and vegetables contain little nitrogenous substance.
Unless the whole of the grain and the legumes form a goodly
proportion of the diet the danger is in consuming too large a bulk of
waste and too much starch in a purely vegetable diet.
In a vegetarian diet, one is liable to eat too freely of cereals; as a
result, the liver becomes clogged and torpid and the stomach and
intestines are deranged and rendered incapable of full digestion and
absorption. The clogged system refuses to assimilate more food.
It follows, therefore, that, unless one is a thorough student of
dietetics, the mixed diet is by far the safest to follow.
One can better run short of starch or fat in one day’s rations than
to be short of protein, because if the two or four ounces daily
requirement is not provided the tissues are consumed and the blood
is impoverished. It is a rare condition in which a reserve of glycogen
and fat is not stored in the system. On the other hand, an excess of
nitrogenous foods calls for a very active circulation and plenty of
oxygen in the system.
It has been held that the vegetarian has a clearer brain, and, if
this be true, it may be due to the fact that he is not eating too much
and thus his system is not overloaded.
Experience, however, does not prove that he has greater mental,
physical, and moral power and efficiency.
In fasting, likewise, the mental power is at first clear and forceful,
but the reason becomes unbalanced if the fast be too prolonged.
A complete diet may be selected without animal flesh, but
including animal products of eggs, milk, cream, and butter, together
with vegetables, fruits, cereals, and nuts, yet, if the vegetable diet
be selected, the legumes, the whole of the grains, and nuts, must be
given their share in each day’s rations.
Each year sees an increase in the number of
travelers. The question of diet many times is of Diet when
great importance. For those of abundant means Traveling
the question is simplified, oftentimes, by the
railway dining-car service, but for those who from economic reasons
must patronize the wayside railway restaurants or other eating
places, the diet question is not so easily solved.
A carefully planned lunch-box is often an aid to the preservation of
regular habits and a preventative of digestive disturbances, due to a
sudden and radical change of diet.
The inactivity and sedentary habit enforced by a long journey, in
which there is small chance for exercise, generally causes
constipation. The shaking of the boat or train also aids this, as it
interrupts normal peristalsis. The motion of the boat or train often
produces nausea and vomiting and thus deranges the digestive
organs.
Greasy or illy prepared food hastily eaten at a lunch counter
provokes various gastric and intestinal ills.
The danger of infected or polluted water complicates the problem,
especially when the sick or infants are involved. Many an attack of
typhoid fever has been traced to the drinking water used during a
vacation trip.
The invention of the vacuum bottle has solved one need of the
traveler. The invention of the electric heater has solved another.
Sterilized and cooled milk may be carried by means of the vacuum
bottle for use with children or the sick, and the portable stove will
enable the boiling and sterilizing of water, when a larger supply is
needed than can be carried in a vacuum bottle. By its means, also, a
hot drink can be prepared for the aged, the invalid, or other
individual, when necessary, as in an emergency.
All fried and greasy food and unripe fruits should be avoided.
One had better lessen the amount of food than suffer the gastric
difficulties occasioned by too much fatty food.
Hard whole wheat crackers with fruit and milk can be had at
almost any eating house. These give a well-balanced meal and are
often preferable to prepared dishes. Fresh fruit, especially the acid
fruits, should form a large part of the diet.
The traveler, on extended journeys, should always provide some of
the easily carried condensed foods, so that if the food obtained by
the way is unpalatable or illy prepared, or in case food is
unobtainable, the needs of the system may be met. Beef meal,
whole wheat or oatmeal crackers, malted milk, chocolate, meat
extracts, etc., occupy little space and may often prove invaluable.
Tablets of soda and also of lime are easily carried and may be
used when soda water or lime water is needed as in nausea or
indigestion.
If it is possible, the water drunk while traveling should be boiled.
The bowels must be kept active and fresh fruits and water are the
best aids in accomplishing this.
The remedies recommended for car sickness or seasickness are
legion; what is an aid in one case is almost or quite without avail in
another. Lemon juice or a slice of lemon in the mouth is generally of
most avail, though lime water in some cases has proven of service.
Attacks can often be mitigated or avoided by not starting on a
journey when overtired, by light eating for several days previous to
beginning a journey, with care in securing good elimination and
plenty of fresh air.
If traveling by boat a reclining chair on deck is far preferable to
lying in a berth in a stuffy stateroom.
Nausea can often be prevented or remedied by deep breathing or
by the sipping of hot water with a little soda.
FOOTNOTES:

[10] For table of weights see pages 357-359.


CHAPTER IX
DIETS

B EFORE giving any diets, let me first of all impress the importance
of eating slowly, of good cheer, of light conversation during a
meal, and of thoroughly masticating the food. Remember it is the
food assimilated which nourishes.
The following diets allow sufficient food for average conditions,
when the vital organs are normal.
Fruit, as previously stated, contains a very small quantity of
nutrition. It is more valuable for its diuretic effect, and to stimulate
the appetite; for this reason it may well be eaten before a meal.
The citrus fruits tend to neutralize too high acidity of the blood,
increasing its alkalinity. For this reason, also, they are best before a
meal, particularly before breakfast; they have a more laxative and
cleansing effect if eaten before the other food. The custom has
been, however, to eat fruits after dinner for dessert and they are so
given in the following menus.
Table XI (page 207) gives the total amount of protein,
carbohydrate, and fat needed daily for the work of the body. The
method of determining the number of calories produced by each
variety of food is also given on page 208.
By a little study of the food one ordinarily eats in connection with
this tabulation and the tables given on pages 233 to 241, it can be
determined whether the food taken each day is well or illy balanced
and whether one is eating too much or not enough.
Table XIII (page 209) gives the balanced supply for a day of the
most commonly used foods and may be consulted as a basis from
which to work in constructing balanced meals.
Because of the wide variation in methods of preparing food in the
home, an exact and absolute standard cannot be fixed.
All foods contain combinations of mineral salts, particularly
calcium (lime), sodium, magnesium, and potassium. In each food,
however, some mineral predominates. For instance, potatoes contain
both calcium and potassium but the potassium content is larger than
the calcium. For this reason when potassium salts are needed in a
diet, potatoes and other potassium-containing foods make a valuable
contribution. When potassium needs to be limited these foods
should be omitted from the diet. When calcium is needed, as in
growing children, calcium-containing foods should be made a large
part of the diet.
In conditions of health the construction of a balanced diet is a
comparatively simple matter. In conditions of disease, however, the
question of diet is often one that can only be solved by a skilled
dietitian, after a chemical analysis. Unfortunately, the number of
these in the United States is not large and their services are not
available in many cases in which they are needed.
A diet in which the acid-forming elements are in excess will
ultimately result in a lessening of the alkalinity of the blood. The
blood then, to maintain its balance, withdraws alkaline substances
from the tissues. A balance must, therefore, be maintained between
the acid and alkaline foods. This has a bearing on scurvy and also in
gout.
Foods which are called acid, that is, they tend to lessen the
normal alkalinity of the blood, are, oats, barley, beef, wheat, eggs,
rice, and maize. When the proportion of acid in the blood is too
great the supply of these foods should be lessened.
Alkaline foods, or those which leave no acid residue, are carrots,
turnips, potatoes, onions, milk, blood, peas, lemon and orange juice,
and beans. These may be used when there is too much acid in the
system.
Neutral foods are sugar, the vegetable oils, and animal fats.
All the content of the foods must be taken into consideration in
building a diet, the carbohydrate, fat, and protein being considered
as well as the mineral. A consideration of the mineral content,
however, should not be neglected. One-eighth grain of iron is taken
daily in the ordinary mixed diet. The fact that in one quart of milk,
according to Hutchinson, there are 1/2 grains of calcium shows how
valuable this food is to the growing child for bone and tissue
building. It must also be considered when constipation results from a
milk diet. Milk and its derivatives are poor in iron, while meat, fish,
potatoes, fruits, and bread are poor in calcium. Animal foods are rich
in sodium; vegetables and fruits in potassium.
The following shows the foods which contain mineral salts, in
larger proportions.

Milk contains 11/2 grams of lime (calcium) in every quart; next in


Calcium lime content come eggs, then cereals, especially rice, radishes,
(lime) asparagus, spinach, veal, olives (16%), apples and strawberries.
Tea, coffee, rhubarb, and cabbage cause deposits of the oxalate of
calcium.
Potassium
Egg yolk, potatoes, apples, lemons, limes, oranges, olives (60%)
Sodium
and strawberries.
Magnesium
Cabbage, asparagus, fibrin of meat, eggs, casein of milk, corn,
Sulphur
turnips, cauliflower, and asparagus.
Yolk of egg, beef, spinach, dandelions, apples, lettuce, lentils,
Iron
strawberries, navy beans, peas, potatoes, wheat, and oatmeal.
Phosphorus Meat and most vegetables.

A knowledge of the carbohydrate content of foods is useful also in


making up a diet, especially in diabetes. Friedenwald and Ruhrah
give the following in their order:
String beans, asparagus, spinach, pickles, lettuce, cucumbers,
Less than 5% greens, celery, Brussels sprouts, rhubarb, sauerkraut, tomatoes,
ripe olives, cauliflower.
Leeks, eggplant, pumpkin, kohlrabi, cabbage, radishes, collards,
watermelon, mushrooms, beets, okra, strawberries, turnips,
From 5 to 10%
lemons, rutabagas, squash, musk melons, peaches, onions,
cranberries.
Blackberries, green onions, oranges, green olives, tomato
From 10 to
catsup, currants, raspberries, apricots, parsnips, pears, apples,
15%
lima beans.
Nectarines, huckleberries, cherries, green peas, almonds,
From 15 to
potatoes, succotash, fresh figs, prunes, grapes, baked beans,
20%
green corn.
Over 20% Plums, boiled potatoes, bananas, sweet potatoes.

In the following menus the effort has been to give a correct


balance of the various food elements with the approximate calories
furnished by each meal. They are suggestive only and may be varied
according to the season of the year, the habits of work, or the tastes
of the individual, care being taken to preserve the relative
proportions.
For instance, if much starch or fat is taken at a meal and little
protein, the balance should swing in the other direction for another
meal, the amount of protein being increased and that of
carbohydrate decreased.
Common sense must rule in the matter, as one individual would be
illy fed on a diet which would be entirely adequate for another of
more sedentary habit and weaker digestion. All the habits of life
such as exercise, breathing, and mental activity must be taken into
consideration.
As previously remarked, there must be a variety in the diet which
will stimulate the appetite, and, unless the tastes of the various
members of a family are capricious, they may be gratified.
If potatoes are not relished rice may be substituted.
Plain bread may be varied by rolls or biscuits.
Well-masticated nuts may supply the protein usually served in
meat and are often a welcome change.
The protein balance is important as this substance is the basis for
growth and repair of the tissues of the body.
When the protein balance of the family meal is provided by meat,
if for any reason one member of the family does not care for meat,
the protein may be supplied by eggs, or by the legumes as shown
on pages 232-234.
Let me repeat that everyone should watch his likes and dislikes in
the matter of food and guard against allowing himself to become
finicky; he should not cultivate a dislike for a food which may
disagree with him at a certain time or the taste of which he does not
like, if that food is wholesome.
Remember that the likes and dislikes for food are largely matters
of cultivation and one misses much enjoyment and much of health
which comes from a well-nourished body by habitually sitting down
to a table in a pessimistic frame of mind because the food served
does not suit the fancy.
It is very difficult for a mother to provide a meal which suits each
member of her family and consideration for her as well as for self
should teach one to guard against a critical attitude.
The following is an example of a badly balanced menu. It was
given a family, including a child, by a mother who “had no time to
study foods. She gave her folks what was the easiest to get and
filled them up the quickest.” This mother may have wasted hours in
gossip with the neighbors, or on “fancy work.”

Breakfast
Rolls with butter
2 cups coffee
Luncheon
Fried sweet potato
Bread and butter
Prunes
Tea
Dinner
Macaroni with cheese
Bread and butter
Boiled potato
Boiled rice with milk
Tea with milk and sugar

The cardinal sin of such a diet is in the lack of protein, the great
predominance of starch, and the inadequate supply of fat. An
excessive amount of sugar, however, was taken in the tea. This was
taken to satisfy the taste, not realizing that the system demanded it
for energy.
The child was given one egg and one slice of bread for breakfast.
Being a light eater it asked for no more, but her mother wondered
why the child was so pale and suffered from constipation.
No water was given with any meal.
There are thousands of such illy nourished children in our schools,
lacking in brain power and readily subject to infection, because of
badly combined or poorly prepared food.
The number of calories in such a diet may suffice to sustain life,
but the balance is insufficient, the amount inadequate, the tissues
are not repaired, the secretions lack some of their necessary
ingredients or are scanty, and the functions of the body are not well
performed.

The following diet is for one who has attained


Sedentary full growth and who exercises no more than to
Occupation walk a few blocks a day. The diet may seem light,
but when one is sitting indoor most of the time,
and has little outdoor exercise, less waste protein is oxidized and
less starch, fat, and sugar are required for heat and energy. If too
much carbonaceous food is consumed, one will store up too much
and become too large. If more protein is consumed than is oxidized
and eliminated one is liable to various derangements of the system.
Every person at sedentary employment should exercise each day
without fail, being particular to bring a thorough circulation to the
vital organs. He should fully inflate his lungs many times a day and
see to it that the air in the room is pure.
In nearly all of the following menus coffee and tea have been
omitted because, as before stated, they are not foods but
stimulants, and the caffein and thein may overstimulate the nerves
and the heart. They sometimes retard digestion. Some other warm
drink should be substituted when there is digestive disturbance, or
when the digestion is weak. They should never at any time be used
strong. They are used simply for their pleasing flavor, or for warmth.
The following diet is suggested for one of sedentary habit who is
not exercising and does not use up much mental or physical energy.

DIET I
Breakfast
Fruit
Cereal coffee or toast coffee
Dry toast (one slice), or one muffin, or one gem
1 slice of crisp bacon
1 egg
If one has taken brisk exercise, or is to take a brisk walk of two or
three miles, a dish of oatmeal or some other cereal, with cream and
sugar, may be added.
Luncheon
Fruit
Creamed soup or purée
Meat, cheese or peanut butter sandwich, or two thin slices of bread and butter
Cup of custard, or one piece of cake, or two cookies
If purée of peas or beans is used the sandwich may be omitted
and one slice of bread is sufficient. If the soup contains much cream
or is made of corn or potato, the cake or cookies may be omitted.
Dinner
Meat, gravy, potatoes or rice
One vegetable (green peas, green beans, cauliflower, greens, corn. Do not use
dried baked beans or dried peas with lean meat)
Salad or fruit
Ice cream or pudding, such as bread, rice, tapioca, cornstarch, or chocolate, or an
easily digested dessert.
Diet II gives the calories of energy required by a business man or
brain worker who uses much mental force.

DIET II
Breakfast
1 orange without sugar 100
1 shredded wheat biscuit with sugar and cream 175
2 slices bacon 75
2 tablespoonfuls creamed potato 160
1 egg 70
2 slices toast with butter 250
1 baked apple 85
2 cups cocoa 80
995
Luncheon
1 bowl oyster stew 250
6 crackers 120
370
Dinner
1/
2 pint clear soup with croutons 75
1 portion beefsteak 433
2 tablespoonfuls green beans 70
2 baked potatoes (medium size) 90
2 slices bread 175
1 pat butter 33
2 tablespoonfuls rice pudding with raisins and cream 450
1326
995
370
2691

Diet III gives approximately the calories required for one taking
moderate exercise.
DIET III
Breakfast
Fruit with sugar 100
2 tablespoonfuls oatmeal with cream and sugar 170
1 piece broiled fish four inches square 205
2 slices buttered toast 250
1 cup coffee with cream and sugar 125
850
Luncheon
2 tablespoonfuls beans baked with bacon 150
1 baked apple with cream 200
1 cup cocoa 68
2 slices bread (thin) with butter 200
618
Dinner
1/
2 pint purée (vegetable) 150
1 portion boiled mutton 300
2 potatoes (medium size) 90
2 slices bread and butter 250
2 tablespoonfuls scalloped tomato 150
2 tablespoonfuls brown betty or peach tapioca with light cream 300
1 cup coffee with cream and sugar 125
1365
850
618
2833
There is no time in life when one needs to be so
For the Girl or watchful of the diet as during these years. Growth
Boy from 13 to is very rapid and much protein is needed to build
21
tissue, particularly to build the red blood
corpuscles. Anemia may be produced by a faulty diet or by one
which lacks eggs, meat, fresh vegetables or fruit, particularly in
developing girls.
The red meats, the yolk of eggs, spinach and all kinds of greens
are important articles of diet at this time, because of the iron which
they contain. They should be supplied freely. Butter and milk are
valuable and regular exercises with deep breathing are imperative.
If the appetite wanes, be sure that the girl or boy is getting
sufficient brisk exercise in the fresh air.
DIET IV
Breakfast
Fruit
Oatmeal, shredded wheat biscuit or triscuit, or some other well cooked cereal with
cream and sugar
One egg, boiled or poached (cooked soft), or chipped beef in cream gravy
Cereal coffee, toast coffee, or hot water with cream and sugar
Buttered toast, gems, or muffins
Luncheon
Cream soup, bean soup, or purée with crackers or dry toast
Bread and butter
Fruit and cake, or rice pudding, or bread, tapioca, cocoanut, or cereal pudding of
any kind, or a cup of custard, or a dish of ice cream
Dinner
Meat (preferably red meat)
Potatoes
Vegetables, preferably spinach, or greens of some kind, or beets boiled with the
tops
Graham bread
Fruit, graham bread toasted or graham wafers. Cake of some simple variety.
Candy (small quantity)
A growing child is usually hungry when it returns from school, and
it is well to give a little easily digested food regularly at this time, but
not sufficient to destroy the appetite for the evening meal. Irregular
eating between meals, however, should be discouraged. An egg
lemonade is easily digested and satisfying. If active and exercising
freely, craving for sweets should be gratified to a limited extent.
The growing boy or girl takes from six to eight glasses of water a
day.
Overeating, however, should be guarded against for many of the
dietary habits of adult life are formed in this period, and the
foundation of many dietetic difficulties and disturbances of the
system are laid.
If one is not hungry at meal time, the chances are that he is not
exercising sufficiently in the fresh air.
Thorough mastication should be insisted on.
One should encourage the habit of eating hard crusts or hard
crackers to exercise the teeth and to insure the swallowing of
sufficient saliva.
The schoolboy or schoolgirl, anxious to be out at play, is especially
liable to bolt the food or to eat an insufficient amount. This should
be especially guarded against and parents should insist on the
proper time being spent at meals.
The dislike for meat or for certain vegetables or articles of food,
which develops in this period, should be guarded against. All
wholesome food should be made a part of the diet and the child
should not be indulged in its likes or dislikes, but should be
instructed in overcoming these.
Very few foods disagree at all times with a normal child and if they
do the cause usually lies in a disordered digestion which needs to be
restored by more careful attention to exercise, deep breathing, and
to elimination of the waste of the system.
The young man active in athletics needs
The Athlete practically the same food as given in Diet IV, yet
more in quantity. He needs to drink water before
his training and at rest periods during the game.
If he is too fat, he should train off the superfluous amount by
exercise and by judiciously abstaining from much sugars, starches,
and fats.
Diets for reduction, however, must be governed by the condition
of the kidneys and the digestive organs.
Deep breathing habits are imperative though he must be careful
not to overtax lungs or heart by hard continuous straining, either at
breathing or at exercise.

The man engaged in muscular work requires


plenty of food; he can digest foods which the The Laboring
professional or business man, or the man of Man
sedentary habits, cannot. He will probably be able
to drink coffee and tea without any disturbance to nerves or to
digestion. In his muscular work he liberates the waste freely and
needs fats, starches, and sugars to supply the heat and energy. This
is especially true of men who work in the fresh air; the muscular
action liberates waste and heat and the full breathing freely oxidizes
the waste, putting it in condition to be excreted through lungs, skin,
kidneys, and intestines.
He should have more meat, eggs, and nitrogenous foods, and he
also needs more carbonaceous foods to supply heat and energy, as
given in Diet V. Three hearty meals a day are necessary.
His muscular movements keep the circulation forceful and the vital
organs strong so that his diet may be almost as heavy as that of the
football player. Meat or eggs, twice a day, with tea or coffee, and
even pie may be eaten with impunity. He needs a good nourishing
breakfast of bacon and eggs or meat, also potatoes, or a liberal
allowance of bread and butter, corn bread, muffins, etc.
DIET V
Breakfast
Calories
4 tablespoonfuls fresh or stewed fruit with sugar 100
3 tablespoonfuls oatmeal with milk and sugar 200
1 portion ham four inches square with fat 200
2 eggs 140
2 cups coffee with cream and sugar 250
2 slices bread and butter 250
1140
Luncheon
2 sandwiches (cheese) 300
1 sandwich (marmalade) 125
1 pint of milk 200
1 slice cake or pie 100
725
Dinner
1/
2 pint oyster stew or vegetable purée 100
2 baked potatoes 100
4 tablespoonfuls macaroni with tomatoes and butter sauce 200
4 slices thick bread and butter 500
2 portions roast beef (fat) 400
2 cups coffee 250
1 slice pie 100
1650
1140
725
3515
The following constitutes an average which will
Condition of Age supply the daily requirement for the aged, or for
one at any age whose organs are not functioning
strongly.

DIET VI
Breakfast
Cereal, well cooked, with cream or sugar. Oatmeal is preferable because it is
laxative
One egg, boiled, poached, or baked (soft)
One slice of toast
Cereal coffee
Dinner
Bouillon or soup
Meat—small portion
Potato (preferably baked)
One vegetable
Cup custard, or bread, rice, or other light pudding with lemon cream sauce
Supper
Soup
Bread and butter
Stewed fruit
Tea

These individuals need little meat. Tea, if used, should not be


strong and, for reasons given on page 104, should never be allowed
to steep.
If the habit of life is active, if one exercises regularly, and if the
constitution is vigorous and the body not too encumbered with fat, a
greater variety and amount of food may be allowed, but great
regularity should be observed concerning the diet and the hours for
meals. Thorough mastication is more than ever a necessity.
If inclined to constipation, or if the kidneys are inactive, grapes or
an apple, or some fruit, well chewed, may be eaten just before
retiring.
Careful attention must be given to securing thorough removal of
waste by attention to the eliminative organs, not overloading them.

TABLES OF USE IN MAKING UP BALANCED DIETS

The following table from Dudley Roberts is of material help in


making up combinations of foodstuffs for balanced diets:
Calories of Grams of
FOOD STUFF Quantity
Energy Protein
Milk 8 oz. 1 glass 160 8.4
Skim milk 8 oz. 1 glass 80 8.0
Cream 8 gm. 1 tsp. 20 0.2
20
Condensed milk (sweetened) hp. tsp. 50 1.8
gm.
Condensed milk
20 ” ” ” 40 2.0
(unsweetened)
Chocolate powd. 10 ” ” ” 90 1.2
Beef juice, beef tea, bouillon,
5 oz. teacup 5-30 1.3
clear soup
Cream soup 8” soup plate 100-250
10
Sugar hp. tsp. 40
gm.
Egg (whole) 50 ” 1 70
Egg (yolk) — 1 55 2.4
10
Butter 1 in. cube 65 0.6
gm.
Cheese ”” ” ” 45 3.0
Meat and fish (lean) 50 ” hp. tbsp. 60 12.0
Meat (medium fat) ”” ” ” 100 7.0
” (very fat) ”” ” ” 150 4.0
Oysters (small) 8” 1 3 0.5
Oysters (large) 25 ” 1 10 1.5
Crackers 3-10 ” 1 12-30 3-6
30-40
Cereals (cooked) teacup 110-150 3-5

Cereals (prepared) 5-7 ” hp. tsp. 18-25 0.5-0.7
Shredded wheat 30 ” 1 100 3.0
Triscuit 15 ” 1 50 1.5
Peas (fresh or canned) 35 ” hp. tbsp. 25 2.0
Peas (dried) 25 ” ” ” 100 6.0
Bean (dried) 25 ” ” ” 90 5.0
Bean (fresh or canned) 30 ” ” ” 30 1.0
Potatoes (medium size) 90 ” 1, 3 in. long 80 1.0
Jelly (sweet) — teacup 50-100 —
Apples 100 ” 1 40 0.2
Oranges 125 ” 1 med. size 60 0.5
Bananas 50 ” 1 med. size 45 0.7
1 saucer
Dried fruit (prunes, etc.) 100 ” 100-200 1-3
medium

The following tables[11] are exceptionally valuable in compiling


diets in various combinations. One can readily determine the number
of grams in various servings of different foods. For example: a small
serving of beef (round), containing some fat, weighs 36 grams; 40
per cent., 14.4 grams, is protein, and 60 per cent., 21.6 grams, is fat
(no carbohydrates). One ordinary thick slice of white, home-made
bread weighs 38 grams; 13 per cent., 4.94 grams, is protein; 6 per
cent., 2.28 grams, is fat, and 81 per cent., 30.78 grams, is
carbohydrate.
The proportion of proteins, carbohydrates, and fats required by
the average individual as suggested on page 208 can be readily
made up from various combinations of foods. Each individual may
ascertain whether he is taking too much food, or too large a
proportion of proteins or of carbohydrates or fats.

TABLE OF 100 FOOD UNITS


“Portion” Wt. of 100
Containing 100 Per cent. of
NAME OF FOOD Calories
Food Units
(approx.) Grams Oz. Proteid Fat Carbohydrate
COOKED MEATS
[13]Beef, r’nd, boiled
Small serving 36 1.3 40 60 00
(fat)
[13]Beef, r’d, boiled
Large serving 62 2.2 90 10 00
(lean)
[13]Beef, r’d, boiled
Small serving 44 1.6 60 40 00
(med.)
[13]Beef, 5th rib,
Half serving 18.5 0.65 12 88 00
roasted
[13]Beef, 5th rib, Very small
25 0.88 18 82 00
roasted s’v’g.
[14]Beef, ribs boiled Small serving 30 1.1 27 73 00
[12]Calves foot jelly 112 4. 19 00 81
[12]Chicken, canned One thin slice 27 0.96 23 77 00
[12]Lamb chops,
broiled, av. One small 27 0.96 24 76 00
chop
[12]Lamb leg, roasted Ord. serving 50 1.8 40 60 00
[13]Mutton, leg, boiled Large serving 34 1.2 35 65 00
[13]Pork, ham, boiled
Small serving 20.5 0.73 14 86 00
(fat)
[13]Pork, ham, boiled Ord. serving 32.5 1.1 28 72 00
[13]Pork, ham, r’st’d
Small Serving 27 0.96 19 81 00
(fat)
[13]Pork, ham, r’st’d
34 1.2 33 67 00
(lean) Small serving
[13]Veal, leg, boiled Large serving 67.5 2.4 73 27 00
VEGETABLES
[12]Artichokes, av.
430 15. 14 0 86
canned
[12]Asparagus, av.
540 19. 33 5 62
canned
[12]Asparagus, av.
206 7.19 18 63 19
cooked
[12]Beans, baked, Small side
75 2.66 21 18 61
canned dish
[12]Beans, Lima, Large side
126 4.44 21 4 75
canned dish
[12]Beans, string,
Five servings 480 16.66 15 48 37
cooked
[12]Beets, edible Three
245 8.7 2 23 75
portion, cooked servings
[12]Cabbage, edible
310 11 20 8 72
portion
Carrots, cooked Two servings 164 5.81 10 34 56
[12]Cauliflower, as
312 11. 23 15 62
purchased
[12]Celery, edible
540 19. 24 5 71
portion
Corn, sweet, cooked One side dish 99 3.5 13 10 77
[12]Cucumbers, edible
565 20. 18 10 72
pt.
[12]Eggplant, edible pt. 350 12. 17 10 73
Lentils, cooked 89 3.15 27 1 72
[12]Lettuce, edible pt. 505 18. 25 14 61
[12]Mushrooms, as
215 7.6 31 8 61
purchased
Onions, fresh, edible
200 7.1 13 5 82
pt.
[12]Onions, cooked 2 large s’v’gs 240 8.4 12 40 48
Parsnips, cooked 163 5.84 10 34 56
[12]Peas, green,
Two servings 178 6.3 25 3 72
canned
[12]Peas, green,
One serving 85 3. 23 27 50
cooked
One good
Potatoes, baked 86 3.05 11 1 88
sized
[12]Potatoes, boiled One large
102 3.62 11 1 88
sized
[12]Potatoes
mashed(creamed) One 89 3.14 10 25 65
serving
[12]Potatoes, chips One-half s’v’g 17 0.6 4 63 33
[12]Potatoes, sweet, Half av.
49 1.7 6 9 85
cooked potato.
[12]Pumpkins, edible
380 13. 15 4 81
pt.
Radishes, as purchased 480 17. 18 3 79
Rhubarb, edible pt. 430 15. 10 27 63
[12]Spinach, cooked Two ord.
174 6.1 15 66 19
s’v’gs
Squash, edible pt. 210 7.4 12 10 78
[12]Succotash, canned Ord. serving 100 3.5 15 9 67
[12]Tomatoes, fresh as
Four av. 430 15. 15 16 69
purchased
Tomatoes, canned 431 15.2 21 7 72
[12]Turnips, edible pt. 2 large s’v’gs 246 8.7 13 4 83
Vegetable oysters 273 9.62 10 51 39
FRUITS (DRIED)
[12]Apples, as
34 1.2 3 7 90
purchased
Apricots, as purchased 35 1.24 7 3 90
[12]Dates, edible
Three large 28 0.99 2 7 91
portion
[12]Dates, as
31 1.1 2 7 91
purchased
[12]Figs, edible portion One large 31 1.1 5 0 95
[12]Prunes, edible
Three large 32 1.14 3 0 97
portion
[12]Prunes, as
38 1.35 3 0 97
purchased
[12]Raisins, edible
28 1. 3 9 88
portion
[12]Raisins, as
31 1.1 3 9 88
purchased
FRUITS (FRESH OR COOKED)
[12]Apples, as
Two apples 206 7.3 3 7 90
purchased
Apples, baked 94 3.3 2 5 93
Apples, sauce Ord. serving 111 3.9 2 5 93
Apricots, cooked Large serving 131 4.61 6 0 94
[12]Bananas, edible pt. One large 100 3.5 5 5 90
[12]Blackberries 170 5.9 9 16 75
Blueberries 128 4.6 3 8 89
[12]Blueberries, canned 165 5.8 4 9 87
Half ord.
Cantaloupe 243 8.6 6 0 94
serv’g
[12]Cherries, edible
124 4.4 5 10 85
portion
[12]Cranberries, as
210 7.5 3 12 85
purchased
[12]Grapes, as
136 4.8 5 15 80
purchased, av.
Grape fruit 215 7.57 7 4 89
Grape juice Small glass 120 4.2 0 0 100
Gooseberries 261 9.2 5 0 95
Lemons 215 7.57 9 14 77
[12]Lemon juice 246 8.77 0 0 100
Nectarines 147 5.18 4 0 96
Olives, ripe About seven 37 1.31 2 91 7
Oranges, as purchased, One very
270 9.4 6 3 91
av. large
[12]Oranges, juice Large glass 188 6.62 0 0 100
Peaches, as purchased, Three
290 10. 7 2 91
av. ordinary
[12]Peaches, sauce Ord. serving 136 4.78 4 2 94
Peaches, juice Ordinary glass 136 4.80 0 0 100
One large
Pears 173 5.40 4 7 89
pear
[12]Pears, sauce 113 3.98 3 4 93
Pineapples, edible p’t’n,
226 8. 4 6 90
av.
[12]Raspberries, black 146 5.18 10 14 76
Raspberries, red 178 6.29 8 0 92
Strawberries, av. Two servings 260 9.1 10 15 75
[12]Watermelon, av. 760 27. 6 6 88
DAIRY PRODUCTS
[12]Butter Ordinary pat. 12.5 0.44 0.5 99.5 00
[12]Buttermilk 11/2 glass 275 9.7 34 12 54
[12]Cheese, Am., pale 11/2 cubic in. 22 0.77 25 73 2
[12]Cheese, cottage 4 cubic in. 89 3.12 76 8 16
[12]Cheese, full cream 11/2 cubic in. 23 0.82 25 73 2
[12]Cheese, Neufchatel 11/2 cubic in. 29.5 1.05 22 76 2
[12]Cheese, Swiss 11/2 cubic in. 23 0.8 25 74 1
[12]Cheese, pineapple 11/2 cubic in. 20 0.72 25 73 2
[12]Cream 1/ ord. glass 49 1.7 5 86 9
4
Kumyss 188 6.7 21 37 42
[12]Milk, condensed,
30 1.06 10 23 67
sweet’nd
[12]Milk, condensed,
59 2.05 24 50 26
unsw’t’nd
[12]Milk, skimmed 11/2 glass 255 9.4 37 7 56
[12]Milk, whole Small glass 140 4.9 19 52 29
Milk, human, 2d week 162 5.7 11 47 42
Milk, human, 3d month 171 6 7 46 47
[12]Whey Two glasses 360 13 15 10 75
CAKES, PASTRY, PUDDINGS, AND DESSERTS
[12]Cake, chocolate Half ord. sq.
28 0.98 7 22 71
layer pc.
[12]Cake, gingerbread Half ord. sq.
27 0.96 6 23 71
pc.
Cake, sponge Small piece 25 0.89 7 25 68
Custard, caramel 71 2.51 19 10 71
Custard, milk Ordinary cup 122 4.29 26 56 18
Two-thirds
Custard, tapioca 69.5 2.45 9 12 79
ord.
[12]Doughnuts Half a
23 0.8 6 45 49
doughnut
[12]Lady fingers Two 27 0.95 10 12 78
[12]Macaroons Four 23 0.82 6 33 61
[12]Pie, apple One-third
38 1.3 5 32 63
piece
[12]Pie, cream One-fourth
30 1.1 5 32 63
pc.
[12]Pie, custard One-third
55 1.9 9 32 59
piece
[12]Pie, lemon One-third
38 1.35 6 36 58
piece
[12]Pie, mince One-fourth
35 1.2 8 38 54
piece
[12]Pie, squash One-third
55 1.9 10 42 48
piece
Pudding, apple sago 81 3.02 6 3 91
Pudding, brown betty Half ord. s’v’g 56.6 2. 7 12 81
Very small
Pudding, cream rice 75 2.65 8 13 79
s’v’g
Pudding, Indian meal Half ord. s’v’g 56.6 2. 12 25 63
Pudding, apple tapioca Small serving 79 2.8 1 1 98
Tapioca, cooked Ord. serving 108 3.85 1 1 98
SWEETS AND PICKLES
[12]Catsup, tomato, av. 170 6. 10 3 87
Candy, plain 26 0.9 0 0 100
Candy, chocolate 30 1.1 1 4 95
[12]Honey Four teasp’ns 30 1.05 1 0 99
[12]Marmalade
28.3 1 0.5 2.5 97
(orange)
Molasses, cane 35 1.2 0.5 0 99.5
[12]Olives, green,
edible portion Five to 32 1.1 1 84 15
seven
[12]Olives, ripe, edible
38 1.3 2 91 7
portion Five to seven
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like