Programming Languages Concepts PDF
Document Details
Uploaded by WelcomeWonder3114
University of Bisha
2007
Robert W. Sebesta
Tags
Summary
This document is a chapter from a textbook on programming languages. It covers preliminaries, topics, reasons for studying programming languages concepts, programming domains, and language evaluation criteria. The content focuses on programming language design, concepts, and evaluation methods.
Full Transcript
Chapter 1 Preliminaries ISBN 0-321-49362-1 Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design Language Categories Language Design Trade-Offs Implementation Methods...
Chapter 1 Preliminaries ISBN 0-321-49362-1 Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design Language Categories Language Design Trade-Offs Implementation Methods Programming Environments Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Reasons for Studying Concepts of Programming Languages Increased ability to express ideas Improved background for choosing appropriate languages Increased ability to learn new languages Better understanding of significance of implementation Overall advancement of computing Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Programming Domains Some examples of programming domains are: computer systems that emulate the decision-making ability of a human expert and are designed to solve complex problems Expert by reasoning through bodies of knowledge. systems: handling interactions between computers and human (natural) Natural- languages such as speech recognition, natural-language language understanding, and natural-language generation. processing: dealing with how computers can understand and automate tasks that the human visual system can do and extracting Computer data from the real world. vision: Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Other programming domains would include: Internet Application scripting Numerical mathematics Array programming Programming education Artificial-intelligence reasoning Relational database querying Cloud computing Software prototyping Computational statistics Symbolic mathematics Contact Management Software Systems design and implementation E-commerce Text processing Financial time-series analysis Theorem proving General-purpose applications Video game programming and development Image processing Video processing Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Language Evaluation Criteria Readability: Writability: the ease with which the ease with which a programs can be read language can be used and understood to create programs Reliability: conformance to Cost: specifications (i.e., the ultimate total cost performs to its specifications) Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Evaluation Criteria: Readability Overall simplicity – A manageable set of features and constructs – Few feature multiplicity (means of doing the same operation) – Minimal operator overloading Orthogonality – A relatively small set of primitive constructs can be combined in a relatively small number of ways – Every possible combination is legal Control statements – The presence of well-known control structures (e.g., while statement) Data types and structures – The presence of adequate facilities for defining data structures Syntax considerations – Identifier forms: flexible composition – Special words and methods of forming compound statements – Form and meaning: self-descriptive constructs, meaningful keywords Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Evaluation Criteria: Writability Simplicity and orthogonality – Few constructs, a small number of primitives, a small set of rules for combining them Support for abstraction – The ability to define and use complex structures or operations in ways that allow details to be ignored Expressivity – A set of relatively convenient ways of specifying operations – Example: the inclusion of for statement in many modern languages Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Evaluation Criteria: Reliability Type checking – Testing for type errors Exception handling – Intercept run-time errors and take corrective measures Aliasing – Presence of two or more distinct referencing methods for the same memory location Readability and writability – A language that does not support “natural” ways of expressing an algorithm will necessarily use “unnatural” approaches, and hence reduced reliability Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Evaluation Criteria: Cost Training programmers to use language Writing programs (closeness to particular applications) Compiling programs Executing programs Language implementation system: availability of free compilers Reliability: poor reliability leads to high costs Maintaining programs Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Evaluation Criteria: Others Portability – The ease with which programs can be moved from one implementation to another Generality – The applicability to a wide range of applications Well-definedness – The completeness and precision of the language’s official definition Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Influences on Language Design Computer Programming Architecture Methodologies – Languages are – New software developed around the development prevalent computer methodologies (e.g., architecture, known object-oriented software as the von Neumann development) led to new architecture programming paradigms and by extension, new programming languages Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 Computer Architecture Influence Well-known computer architecture: Von Neumann Imperative languages, most dominant, because of von Neumann computers – Data and programs stored in memory – Memory is separate from CPU – Instructions and data are piped from memory to CPU – Basis for imperative languages Variables model memory cells Assignment statements model piping Iteration is efficient Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 The von Neumann Architecture Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Programming Methodologies Influences 1950s and early 1960s: Simple applications; worry about machine efficiency Late 1960s: People efficiency became important; readability, better control structures – structured programming – top-down design and step-wise refinement Late 1970s: Process-oriented to data-oriented – data abstraction Middle 1980s: Object-oriented programming – Data abstraction + inheritance + polymorphism Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Language Categories Imperative – Central features are variables, assignment statements, and iteration – Examples: C, Pascal Functional – Main means of making computations is by applying functions to given parameters – Examples: LISP, Scheme Logic – Rule-based (rules are specified in no particular order) – Example: Prolog Object-oriented – Data abstraction, inheritance, late binding – Examples: Java, C++ Markup – New; not a programming per se, but used to specify the layout of information in Web documents – Examples: XHTML, XML Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Language Design Trade-Offs Reliability vs. cost of execution Conflicting criteria❑ Example: Java demands all references to array elements be checked for proper indexing but that leads to increased execution costs Readability vs. writability Another conflicting criteria❑ Example: APL provides many powerful operators (and a large number of new symbols), allowing complex computations to be written in a compact program but at the cost of poor readability Writability (flexibility) vs. reliability Another conflicting criteria❑ Example: C++ pointers are powerful and very flexible but not reliably used Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Implementation Methods Hybrid Compilation Pure Interpretation Implementation Systems Programs are interpreted A compromise between Programs are translated by another program known compilers and pure into machine language as an interpreter interpreters Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Layered View of Computer The operating system and language implementation are layered over Machine interface of a computer Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Compilation Translate high-level program (source language) into machine code (machine language) Slow translation, fast execution Compilation process has several phases: – lexical analysis: converts characters in the source program into lexical units – syntax analysis: transforms lexical units into parse trees which represent the syntactic structure of program – Semantics analysis: generate intermediate code – code generation: machine code is generated Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 The Compilation Process Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Additional Compilation Terminologies Load module (executable image): the user and system code together Linking and loading: the process of collecting system program and linking them to user program Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Execution of Machine Code Fetch-execute-cycle (on a von Neumann architecture) initialize the program counter repeat forever fetch the instruction pointed by the counter increment the counter decode the instruction execute the instruction end repeat Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Von Neumann Bottleneck Connection speed between a computer’s memory and its processor determines the speed of a computer Program instructions often can be executed a lot faster than the above connection speed; the connection speed thus results in a bottleneck Known as von Neumann bottleneck; it is the primary limiting factor in the speed of computers Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Pure Interpretation No translation Easier implementation of programs (run-time errors can easily and immediately displayed) Slower execution (10 to 100 times slower than compiled programs) Often requires more space Becoming rare on high-level languages Significant comeback with some Web scripting languages (e.g., JavaScript) Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Pure Interpretation Process Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Hybrid Implementation Systems A compromise between compilers and pure interpreters A high-level language program is translated to an intermediate language that allows easy interpretation Faster than pure interpretation Examples – Perl programs are partially compiled to detect errors before interpretation – Initial implementations of Java were hybrid; the intermediate form, byte code, provides portability to any machine that has a byte code interpreter and a run-time system (together, these are called Java Virtual Machine) Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Hybrid Implementation Process Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Just-in-Time Implementation Systems Initially translate programs to an intermediate language Then compile intermediate language into machine code Machine code version is kept for subsequent calls JIT systems are widely used for Java programs.NET languages are implemented with a JIT system Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Preprocessors Preprocessor macros (instructions) are commonly used to specify that code from another file is to be included A preprocessor processes a program immediately before the program is compiled to expand embedded preprocessor macros A well-known example: C preprocessor – expands #include, #define, and similar macros Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Programming Environments Borland The collection JBuilder of tools used An integrated development in software environment for development Java UNIX Microsoft Visual An older operating Studio.NET system and tool A large, complex collection visual environment Nowadays often used Used to program in through a GUI (e.g., CDE, C#, Visual BASIC.NET, KDE, or GNOME) that run Jscript, J#, or C++ on top of UNIX 1-31 Copyright © 2007 Addison-Wesley. All rights reserved. Summary The study of programming languages is valuable for a number of reasons: – Increase our capacity to use different constructs – Enable us to choose languages more intelligently – Makes learning new languages easier Most important criteria for evaluating programming languages include: – Readability, writability, reliability, cost Major influences on language design have been machine architecture and software development methodologies The major methods of implementing programming languages are: compilation, pure interpretation, and hybrid implementation Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Questions: 1. Write short notes on languages categories with examples. 2. Define pure interpretation and draw the diagram. 3. Explain compilation and draw the process diagram of it. 4. Write the different type of programming domains. 5. Define hybrid implementation and draw the process diagram of it. 6. Write the following terms: i. type checking ii. exception handling iii. Aliasing 7. Explain following terms: i. compilation ii. Pure interpretation iii. Hybrid implementation system 8. Define following terms: i. load module ii. Loading and linking iii. preprocessors 1-33 Chapter 2 Describing Syntax and Semantics ISBN 0-321-49362-1 Chapter 2 Topics Introduction The General Problem of Describing Syntax Formal Methods of Describing Syntax Attribute Grammars Describing the Meanings of Programs: Dynamic Semantics Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Part 1 Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Introduction Syntax: the form or structure of the expressions, statements, and program units Semantics: the meaning of the expressions, statements, and program units Syntax and semantics provide a language’s definition – Users of a language definition Other language designers Implementers Programmers (the users of the language) Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 The General Problem of Describing Syntax: Terminology A sentence is a string of characters over some alphabet A language is a set of sentences A lexeme is the lowest level syntactic unit of a language (e.g., *, sum, begin) A token is a category of lexemes (e.g., identifier) Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Exp: Token Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Formal Definition of Languages Recognizers – A recognition device reads input strings of the language and decides whether the input strings belong to the language – Example: syntax analysis part of a compiler – Detailed discussion in Chapter 4 Generators – A device that generates sentences of a language – One can determine if the syntax of a particular sentence is correct by comparing it to the structure of the generator Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Formal Methods of Describing Syntax Context-Free Grammars – Developed by Noam Chomsky in the mid-1950s – Language generators, meant to describe the syntax of natural languages – Define a class of languages called context-free languages Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Backus-Naur Form (BNF) Backus-Naur Form (1959) – Invented by John Backus to describe Algol 58 – BNF is equivalent to context-free grammars – BNF is a metalanguage used to describe another language Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 BNF Fundamentals Non-terminals: BNF abstractions Terminals: lexemes and tokens Grammar: a collection of rules – Examples of BNF rules: Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 BNF Rules A rule has a left-hand side (LHS) and a right-hand side (RHS), and consists of terminal and nonterminal symbols A grammar is a finite nonempty set of rules An abstraction (or nonterminal symbol) can have more than one RHS → | begin end Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Describing Lists Syntactic lists are described using recursion → ident | ident, A derivation is a repeated application of rules, starting with the start symbol and ending with a sentence (all terminal symbols) Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 An Example Grammar 1 → < stmt_list > → | ; → = → A | B | C → + | - | Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 An Example Derivation Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Derivation Every string of symbols in the derivation is a sentential form A sentence is a sentential form that has only terminal symbols Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 An Example Grammar → = → A | B | C → + | * | Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 An Example Derivation Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Parse Tree A hierarchical representation of a derivation Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Ambiguity in Grammars A grammar is ambiguous if and only if it generates a sentential form that has two or more distinct parse trees Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 An Ambiguous Expression Grammar → | const → / | - const - const / const const - const / const Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 An Unambiguous Expression Grammar If we use the parse tree to indicate precedence levels of the operators, we cannot have ambiguity → - | → / const | const - / const const const Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Associativity of Operators Operator associativity can also be indicated by a grammar -> + | const (ambiguous) -> + const | const (unambiguous) + + expr expr + expr const + expr const const const const const Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Associativity of Operators -> + | const (ambiguous) -> + const | const (unambiguous) + const + expr const Copyright © 2007 Addison-Wesley. All rights reserved. Chapter 3 Data Types ISBN 0-321—49362-1 Chapter 6 Topics Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types Associative Arrays Record Types Union Types Pointer and Reference Types Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Introduction A data type defines a collection of data objects and a set of predefined operations on those objects A descriptor is the collection of the attributes of a variable An object represents an instance of a user-defined (abstract data) type One design issue for all data types: What operations are defined and how are they specified? Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Primitive data types Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Primitive Data Types Almost all programming languages provide a set of primitive data types Primitive data types: Those not defined in terms of other data types Some primitive data types are merely reflections of the hardware Others require little non-hardware support Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Primitive Data Types Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Primitive Data Types: Integer Almost always an exact reflection of the hardware so the mapping is trivial There may be as many as eight different integer types in a language Java’s signed integer sizes: byte, short, int, long Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Primitive Data Types: Floating Point Model real numbers, but only as approximations Languages for scientific use support at least two floating-point types (e.g., float and double; sometimes more Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Primitive Data Types: Decimal For business applications (money) – Essential to COBOL – C# offers a decimal data type Store a fixed number of decimal digits Advantage: accuracy Disadvantages: limited range, wastes memory Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Primitive Data Types: Boolean Simplest of all Range of values: two elements, one for “true” and one for “false” Could be implemented as bits, but often as bytes – Advantage: readability Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Primitive Data Types: Character Stored as numeric codings Most commonly used coding: American Standard Code for Information Interchange ASCII Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 Character string types Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 Character String Types Values are sequences of characters Design issues: – Is it a primitive type or just a special kind of array? – Should the length of strings be static or dynamic? Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Character String Types Operations Typical operations: – Assignment and copying – Comparison (=, >, etc.) – Catenation – Substring reference – Pattern matching Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Character String Type in Certain Languages C and C++ – Not primitive – Use char arrays and a library of functions that provide operations SNOBOL4 (a string manipulation language) – Primitive – Many operations, including elaborate pattern matching Java – Primitive via the String class Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Character String Length Options Static Length Strings: COBOL, Java’s String class Limited Dynamic Length Strings : C and C++ – In C-based language, a special character is used to indicate the end of a string’s characters, rather than maintaining the length Dynamic (no maximum) Length Strings : SNOBOL4, Perl, JavaScript Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Character String Implementation Static length: compile-time descriptor Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Character String Implementation Limited dynamic length: may need a run- time descriptor for length (but not in C and C+ +) Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Character String Implementation Dynamic length: need run-time descriptor; allocation/de-allocation is the biggest implementation problem Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Enumeration types Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Enumeration Types All possible values, which are named constants, are provided in the definition C# example enum days {mon, tue, wed, thu, fri, sat, sun}; Or enum days {mon=2, tue, wed, thu, fri, sat, sun}; Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Evaluation of Enumerated Type Aid to readability, e.g., no need to code a color as a number Aid to reliability, e.g., compiler can check: – operations (don’t allow colors to be added) – No enumeration variable can be assigned a value outside its defined range Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Array types Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Array Types An array is an aggregate of homogeneous data elements in which an individual element is identified by its position in the aggregate, relative to the first element. Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Array Indexing Indexing (or subscripting) is a mapping from indices to elements array_name (index_value_list) → an element Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Arrays Index (Subscript) Types Two distinct types are involved in an array type: 1. The element type 2. The type of the subscripts E.g double temp (element type is double) (10 is index) FORTRAN, C: integer only Java: integer types only Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Subscript Binding and Array Categories 1- Static: subscript ranges are statically bound and storage allocation is static (before run-time) – Advantage: efficiency (no dynamic allocation) 2- Fixed stack-dynamic: subscript ranges are statically bound, but the allocation is done at declaration time – Advantage: space efficiency Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Subscript Binding and Array Categories (continued) 3- Fixed heap-dynamic: similar to fixed stack-dynamic: storage binding is dynamic but fixed after allocation 4- Heap-dynamic: binding of subscript ranges and storage allocation is dynamic and can change any number of times – Advantage: flexibility Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Array Initialization Some language allow initialization at the time of storage allocation – C, C++, Java, C# example int list [] = {4, 5, 7, 83} – Character strings in C and C++ char name [] = “freddie”; Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Rectangular and Jagged Arrays A rectangular array is a multi-dimensioned array in which all of the rows have the same number of elements and all columns have the same number of elements A jagged matrix has rows with varying number of elements Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Slices A slice is some substructure of an array; nothing more than a referencing mechanism Slices are only useful in languages that have array operations Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 Slice Examples Python Vector = [2, 4, 6, 8, 10, 12, 14, 16] Mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] Vector (3:6) is a three element array ( those elements with the subscripts 3,4 and 5) mat [0:2] is the first and second element of the first row of mat Copyright © 2007 Addison-Wesley. All rights reserved. 1-34 Summary The data types of a language are a large part of what determines that language’s style and usefulness The primitive data types of most imperative languages include numeric, character, and Boolean types Arrays and records are included in most languages Pointers are used for addressing flexibility and to control dynamic storage management Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 Questions: 1. Define array with an example. 2. Explain slice concept with an example. 2. What is exception and write a program to explain array index out of bound exception. 3. Define following terms: i. Static length ii. Dynamic length iii. Garbage collector 4. Write the following terms: i. Rectangular array ii. Jagged array 1-36 Chapter 4 Names, Bindings, Type Checking, and Scopes ISBN 0-321-49362-1 Chapter 4 Topics Introduction Names Variables The Concept of Binding Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative languages are abstractions of von Neumann architecture – Memory Stores both instructions and data – Processor provides operations for modifying the contents. of the memory. Variables characterized by attributes – Type: to design, must consider scope, lifetime, type checking, initialization, and type compatibility 1-3 Names Design issues for names: – Are names case sensitive? – Are special words reserved words or keywords? A Name is a strings of characters used to identify some entity in a program. Name in most programming languages have the same form: a letter followed by a string consisting of letters, digits, and underscore characters (_). 1-4 Names (continued) Length – If too short, they cannot be connotative – Language examples: FORTRAN I: maximum 6 COBOL: maximum 30 FORTRAN 90 and ANSI C: maximum 31 C# and Java: no limit, and all are significant C++: no limit, but implementers often impose one 1-5 Names (continued) Case sensitivity – Disadvantage: readability (names that look alike are different) – C, C++, and Java names are case sensitive The names in other languages are not 1-6 Names (continued) Special words – An aid to readability; used to delimit or separate statement clauses A keyword is a word that is special only in certain contexts, e.g., in Fortran – Real VarName (Real is a data type followed with a name, therefore Real is a keyword) – A reserved word is a special word that cannot be used as a user-defined name 1-7 Variables A variable is an abstraction of a memory cell Variables can be characterized as a sextuple of attributes: – Name – Address – Value – Type – Lifetime – Scope 1-8 Variables Attributes Name - not all variables have them Address - the memory address with which it is associated – A variable may have different addresses at different places in a program – If two variable names can be used to access the same memory location, they are called aliases – Aliases are created via pointers, reference variables, C and C++ unions 1-9 Variables Attributes (continued) Type – determines the range of values of variables and the set of operations that are defined for values of that type; in the case of floating point, type also determines the precision Value - the contents of the location with which the variable is associated 1-10 The Concept of Binding A binding is an association, between an attribute and an entity, such as between a variable and type or value, or between an operation and a symbol Binding time is the time at which a binding takes place. 1-11 Possible Binding Times Language design time -- bind operator symbols to operations Language implementation time-- bind floating point type to a representation Compile time -- bind a variable to a type in C or Java Load time -- bind a C or C++ variable to a memory cell Runtime -- bind a nonstatic local variable to a memory cell 1-12 Static and Dynamic Binding A binding is static if it first occurs before run time and remains unchanged throughout program execution. A binding is dynamic if it first occurs during execution or can change during execution of the program 1-13 Dynamic Type Binding Dynamic Type Binding (JavaScript and PHP) Specified through an assignment statement e.g., JavaScript list = [2, 4.33, 6, 8]; list = 17.3; – Advantage: flexibility (generic program units) – Disadvantages: High cost (dynamic type checking and interpretation) Type error detection by the compiler is difficult 1-14 Variable Attributes (continued) Storage Bindings & Lifetime – Allocation - getting a cell from some pool of available cells – Deallocation - putting a cell back into the pool The lifetime of a variable is the time during which it is bound to a particular memory cell 1-15 Categories of Variables by Lifetimes Static--bound to memory cells before execution begins and remains bound to the same memory cell throughout execution, – Advantages: efficiency – Disadvantage: lack of flexibility (no recursion) 1-16 Categories of Variables by Lifetimes Stack-dynamic--Storage bindings are created for variables when their declaration statements are elaborated. Advantage: allows recursion; conserves storage Disadvantages: Overhead of allocation and deallocation 1-17 Categories of Variables by Lifetimes Explicit heap-dynamic Allocated and deallocated by explicit directives specified by the programmer, which take effect during execution Advantage: provides for dynamic storage management Disadvantage: inefficient and unreliable 1-18 Categories of Variables by Lifetimes Implicit heap-dynamic--Allocation and deallocation caused by assignment statements Advantage: flexibility Disadvantages: Loss of error detection 1-19 1-20 Variable Attributes: Scope The scope of a variable is the range of statements over which it is visible The nonlocal variables of a program unit are those that are visible but not declared there The scope rules of a language determine how references to names are associated with variables 1-21 Static Scope Based on program text To connect a name reference to a variable, you (or the compiler) must find the declaration Search process: search declarations, first locally, then in increasingly larger enclosing scopes, until one is found for the given name Enclosing static scopes (to a specific scope) are called its static ancestors; the nearest static ancestor is called a static parent 1-22 Scope (continued) Variables can be hidden from a unit by having a "closer" variable with the same name C++ and Ada allow access to these "hidden" variables – In Ada: unit.name – In C++: class_name::name 1-23 Blocks – A method of creating static scopes inside program units--from ALGOL 60 – Examples: C and C++: for (...) { int index;... } Ada: declare LCL : FLOAT; begin... end 1-24 Evaluation of Static Scoping Assume MAIN calls A and B A calls C and D B calls A and E MAIN MAIN A C A B D C D E B E 1-25 Static Scope Example MAIN MAIN A B A B C D E C D E Desirable call graph Potential call graph 1-26 Static Scope (continued) Suppose the spec is changed so that D must now access some data in B Solutions: – Put D in B (but then C can no longer call it and D cannot access A's variables) – Move the data from B that D needs to MAIN (but then all procedures can access them) Same problem for procedure access Overall: static scoping often encourages many globals 1-27 Dynamic Scope Based on calling sequences of program units, not their textual layout References to variables are connected to declarations by searching back through the chain of subprogram calls that forced execution to this point 1-28 Scope Example MAIN - declaration of x SUB1 - declaration of x -... call SUB2... MAIN calls SUB1 SUB1 calls SUB2 SUB2 SUB2 uses x... - reference to x -...... call SUB1 … 1-29 Scope Example Static scoping – Reference to x is to MAIN's x Dynamic scoping – Reference to x is to SUB1's x Evaluation of Dynamic Scoping: – Advantage: convenience – Disadvantage: poor readability 1-30 Scope and Lifetime Scope and lifetime are sometimes closely related, but are different concepts 1-31 Referencing Environments The referencing environment of a statement is the collection of all names that are visible in the statement In a static-scoped language, it is the local variables plus all of the visible variables in all of the enclosing scopes A subprogram is active if its execution has begun but has not yet terminated In a dynamic-scoped language, the referencing environment is the local variables plus all visible variables in all active subprograms 1-32 Named Constants A named constant is a variable that is bound to a value only when it is bound to storage Advantages: readability and modifiability Used to parameterize programs The binding of values to named constants can be either static (called manifest constants) or dynamic Languages: – FORTRAN 90: constant-valued expressions – Ada, C++, and Java: expressions of any kind 1-33 Summary Case sensitivity and the relationship of names to special words represent design issues of names Variables are characterized by the sextuples: name, address, value, type, lifetime, scope Binding is the association of attributes with program entities Scalar variables are categorized as: static, stack dynamic, explicit heap dynamic, implicit heap dynamic Strong typing means detecting all type errors 1-34 5 Difference between Control Statement and Control Structure? 6 6 Subprograms A subprogram parameter can be specified with a mode, which is one of the following: Types of Subprograms Chapter 6 Expressions and Assignment Statements ISBN 0-321-49362-1 Chapter 5 Topics Introduction Arithmetic Expressions Overloaded Operators Type Conversions Relational and Boolean Expressions Short-Circuit Evaluation Assignment Statements Mixed-Mode Assignment Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Introduction Expressions are the fundamental means of specifying computations in a programming language To understand expression evaluation, need to be familiar with the orders of operator and operand evaluation Essence of imperative languages is dominant role of assignment statements Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Arithmetic Expressions Arithmetic evaluation was one of the motivations for the development of the first programming languages Arithmetic expressions consist of operators, operands, parentheses, and function calls Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Arithmetic Expressions: Design Issues Design issues for arithmetic expressions – operator precedence rules – operator associativity rules – order of operand evaluation – operand evaluation side effects – operator overloading – mode mixing expressions Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Arithmetic Expressions: Operators A unary operator has one operand A binary operator has two operands A ternary operator has three operands Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Arithmetic Expressions: Operator Precedence Rules The operator precedence rules for expression evaluation define the order in which “adjacent” operators of different precedence levels are evaluated Typical precedence levels – parentheses – unary operators – ** (if the language supports it) – *, / – +, - Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Arithmetic Expressions: Operator Associativity Rule The operator associativity rules for expression evaluation define the order in which adjacent operators with the same precedence level are evaluated Typical associativity rules – Left to right, except **, which is right to left – Sometimes unary operators associate right to left (e.g., in FORTRAN) APL is different; all operators have equal precedence and all operators associate right to left Precedence and associativity rules can be overriden with parentheses Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Arithmetic Expressions: Conditional Expressions Conditional Expressions – C-based languages (e.g., C, C++) – An example: average = (count == 0)? 0 : sum / count – Evaluates as if written like if (count == 0) average = 0 else average = sum /count Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Arithmetic Expressions: Operand Evaluation Order Operand evaluation order 1. Variables: fetch the value from memory 2. Constants: sometimes a fetch from memory; sometimes the constant is in the machine language instruction 3. Parenthesized expressions: evaluate all operands and operators first Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Arithmetic Expressions: Potentials for Side Effects Functional side effects: when a function changes a two-way parameter or a non-local variable Problem with functional side effects: – When a function referenced in an expression alters another operand of the expression; e.g., for a parameter change: a = 10; b = a + fun(a); Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Functional Side Effects Two possible solutions to the problem 1. Write the language definition to disallow functional side effects No two-way parameters in functions No non-local references in functions Advantage: it works! Disadvantage: inflexibility of two-way parameters and non-local references 2. Write the language definition to demand that operand evaluation order be fixed Disadvantage: limits some compiler optimizations Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 Overloaded Operators Use of an operator for more than one purpose is called operator overloading Some are common (e.g., + for int and float) Some are potential trouble (e.g., * in C and C++) – Loss of compiler error detection (omission of an operand should be a detectable error) – Some loss of readability – Can be avoided by introduction of new symbols (e.g., Pascal’s div for integer division) Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 Overloaded Operators (continued) C++ and Ada allow user-defined overloaded operators Potential problems: – Users can define nonsense operations – Readability may suffer, even when the operators make sense Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Type Conversions A narrowing conversion is one that converts an object to a type that cannot include all of the values of the original type e.g., float to int A widening conversion is one in which an object is converted to a type that can include at least approximations to all of the values of the original type e.g., int to float Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Type Conversions: Mixed Mode A mixed-mode expression is one that has operands of different types A coercion is an implicit type conversion Disadvantage of coercions: – They decrease in the type error detection ability of the compiler In most languages, all numeric types are coerced in expressions, using widening conversions In Ada, there are virtually no coercions in expressions Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Explicit Type Conversions Explicit Type Conversions Called casting in C-based language Examples – C: (int) angle – Ada: Float (sum) Note that Ada’s syntax is similar to function calls Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 Type Conversions: Errors in Expressions Causes – Inherent limitations of arithmetic e.g., division by zero – Limitations of computer arithmetic e.g. overflow Often ignored by the run-time system Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 Relational and Boolean Expressions Relational Expressions – Use relational operators and operands of various types – Evaluate to some Boolean representation – Operator symbols used vary somewhat among languages (!=, /=,.NE., , #) Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Relational and Boolean Expressions Boolean Expressions – Operands are Boolean and the result is Boolean – Example operators FORTRAN 77 FORTRAN 90 C Ada.AND. and && and.OR. or || or.NOT. not ! not xor Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Relational and Boolean Expressions: No Boolean Type in C C has no Boolean type--it uses int type with 0 for false and nonzero for true One odd characteristic of C’s expressions: a < b < c is a legal expression, but the result is not what you might expect: – Left operator is evaluated, producing 0 or 1 – The evaluation result is then compared with the third operand (i.e., c) Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Relational and Boolean Expressions: Operator Precedence Precedence of C-based operators postfix ++, -- unary +, -, prefix ++, --, ! *,/,% binary +, - , = =, != && || Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Short Circuit Evaluation An expression in which the result is determined without evaluating all of the operands and/or operators Example: (13*a) * (b/13–1) If a is zero, there is no need to evaluate (b/13-1) Problem with non-short-circuit evaluation index = 1; while (index < length) && (LIST[index] != value) index++; – When index=length, LIST [index] will cause an indexing problem (assuming LIST has length -1 elements) Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Short Circuit Evaluation (continued) C, C++, and Java: use short-circuit evaluation for the usual Boolean operators (&& and ||), but also provide bitwise Boolean operators that are not short circuit (& and |) Ada: programmer can specify either (short-circuit is specified with and then and or else) Short-circuit evaluation exposes the potential problem of side effects in expressions e.g. (a > b) || (b++ / 3) Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Assignment Statements The general syntax The assignment operator = FORTRAN, BASIC, PL/I, C, C++, Java := ALGOLs, Pascal, Ada = can be bad when it is overloaded for the relational operator for equality Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Assignment Statements: Conditional Targets Conditional targets (C, C++, and Java) (flag)? total : subtotal = 0 Which is equivalent to if (flag) total = 0 else subtotal = 0 Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Assignment Statements: Compound Assignment Operators A shorthand method of specifying a commonly needed form of assignment Introduced in ALGOL; adopted by C Example a = a + b is written as a += b Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Assignment Statements: Unary Assignment Operators Unary assignment operators in C-based languages combine increment and decrement operations with assignment Examples count++ (count incremented) --count (count decremented) Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Assignment as an Expression In C, C++, and Java, the assignment statement produces a result and can be used as operands An example: while ((ch = getchar())!= EOF){…} ch = getchar() is carried out; the result (assigned to ch) is used as a conditional value for the while statement Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Mixed-Mode Assignment Assignment statements can also be mixed-mode, for example int a, b; float c; c = a / b; In Pascal, integer variables can be assigned to real variables, but real variables cannot be assigned to integers In Java, only widening assignment coercions are done In Ada, there is no assignment coercion Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 Summary Expressions Operator precedence and associativity Operator overloading Mixed-type expressions Various forms of assignment Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Chapter 5 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction to Event Handling Event Handling with Java Copyright © 2007 Addison-Wesley. All rights reserved. 1-2 Introduction to Exception Handling In a language without exception handling – When an exception occurs, control goes to the operating system, where a message is displayed and the program is terminated In a language with exception handling – Programs are allowed to trap some exceptions, thereby providing the possibility of fixing the problem and continuing Copyright © 2007 Addison-Wesley. All rights reserved. 1-3 Basic Concepts Many languages allow programs to trap input/output errors (including EOF) An exception is any unusual event, either erroneous or not, detectable by either hardware or software, that may require special processing The special processing that may be required after detection of an exception is called exception handling The exception handling code unit is called an exception handler Copyright © 2007 Addison-Wesley. All rights reserved. 1-4 Exception Handling Alternatives An exception is raised when its associated event occurs A language that does not have exception handling capabilities can still define, detect, raise, and handle exceptions (user defined, software detected) Alternatives: – Send an auxiliary parameter or use the return value to indicate the return status of a subprogram – Pass a label parameter to all subprograms (error return is to the passed label) – Pass an exception handling subprogram to all subprograms Copyright © 2007 Addison-Wesley. All rights reserved. 1-5 Advantages of Built-in Exception Handling Error detection code is tedious to write and it clutters the program Exception propagation allows a high level of reuse of exception handling code Copyright © 2007 Addison-Wesley. All rights reserved. 1-6 Design Issues (continued) How and where are exception handlers specified and what is their scope? How is an exception occurrence bound to an exception handler? Where does execution continue, if at all, after an exception handler completes its execution? How are user-defined exceptions specified? Copyright © 2007 Addison-Wesley. All rights reserved. 1-7 Design Issues Should there be default exception handlers for programs that do not provide their own? Can built-in exceptions be explicitly raised? Are hardware-detectable errors treated as exceptions that can be handled? Are there any built-in exceptions? How can exceptions be disabled, if at all? Copyright © 2007 Addison-Wesley. All rights reserved. 1-8 Exception Handling Control Flow Copyright © 2007 Addison-Wesley. All rights reserved. 1-9 Exception Handling in Ada An exception handler in Ada can occur in either a subprogram body, a package body, a task, or a block Because exception handlers are usually local to the code in which the exception can be raised, they do not have parameters Copyright © 2007 Addison-Wesley. All rights reserved. 1-10 Ada Exception Handlers Handler form: when exception_choice{|exception_choice} => statement_sequence exception_choice form: exception_name | others Handlers are placed at the end of the block or unit in which they occur Copyright © 2007 Addison-Wesley. All rights reserved. 1-11 Binding Exceptions to Handlers If the block or unit in which an exception is raised does not have a handler for that exception, the exception is propagated elsewhere to be handled – Procedures - propagate it to the caller – Blocks - propagate it to the scope in which it appears – Package body - propagate it to the declaration part of the unit that declared the package (if it is a library unit, the program is terminated) – Task - no propagation; if it has a handler, execute it; in either case, mark it "completed" Copyright © 2007 Addison-Wesley. All rights reserved. 1-12 Continuation The block or unit that raises an exception but does not handle it is always terminated (also any block or unit to which it is propagated that does not handle it) Copyright © 2007 Addison-Wesley. All rights reserved. 1-13 Other Design Choices User-defined Exceptions form: exception_name_list : exception; Raising Exceptions form: raise [exception_name] – (the exception name is not required if it is in a handler--in this case, it propagates the same exception) Exception conditions can be disabled with: pragma SUPPRESS(exception_list) Copyright © 2007 Addison-Wesley. All rights reserved. 1-14 Predefined Exceptions CONSTRAINT_ERROR - index constraints, range constraints, etc. NUMERIC_ERROR - numeric operation cannot return a correct value (overflow, division by zero, etc.) PROGRAM_ERROR - call to a subprogram whose body has not been elaborated STORAGE_ERROR - system runs out of heap TASKING_ERROR - an error associated with tasks Copyright © 2007 Addison-Wesley. All rights reserved. 1-15 Evaluation The Ada design for exception handling embodies the state-of-the-art in language design in 1980 A significant advance over PL/I Ada was the only widely used language with exception handling until it was added to C++ Copyright © 2007 Addison-Wesley. All rights reserved. 1-16 Exception Handling in C++ Added to C++ in 1990 Design is based on that of CLU, Ada, and ML Copyright © 2007 Addison-Wesley. All rights reserved. 1-17 C++ Exception Handlers Exception Handlers Form: try { -- code that is expected to raise an exception } catch (formal parameter) { -- handler code }... catch (formal parameter) { -- handler code } Copyright © 2007 Addison-Wesley. All rights reserved. 1-18 The catch Function catch is the name of all handlers--it is an overloaded name, so the formal parameter of each must be unique The formal parameter need not have a variable – It can be simply a type name to distinguish the handler it is in from others The formal parameter can be used to transfer information to the handler The formal parameter can be an ellipsis, in which case it handles all exceptions not yet handled Copyright © 2007 Addison-Wesley. All rights reserved. 1-19 Throwing Exceptions Exceptions are all raised explicitly by the statement: throw [expression]; The brackets are metasymbols A throw without an operand can only appear in a handler; when it appears, it simply re-raises the exception, which is then handled elsewhere The type of the expression disambiguates the intended handler Copyright © 2007 Addison-Wesley. All rights reserved. 1-20 Unhandled Exceptions An unhandled exception is propagated to the caller of the function in which it is raised This propagation continues to the main function If no handler is found, the program is terminated Copyright © 2007 Addison-Wesley. All rights reserved. 1-21 Continuation After a handler completes its execution, control flows to the first statement after the last handler in the sequence of handlers of which it is an element Other design choices – All exceptions are user-defined – Exceptions are neither specified nor declared – Functions can list the exceptions they may raise – Without a specification, a function can raise any exception (the throw clause) Copyright © 2007 Addison-Wesley. All rights reserved. 1-22 Evaluation It is odd that exceptions are not named and that hardware- and system software- detectable exceptions cannot be handled Binding exceptions to handlers through the type of the parameter certainly does not promote readability Copyright © 2007 Addison-Wesley. All rights reserved. 1-23 Exception Handling in Java Based on that of C++, but more in line with OOP philosophy All exceptions are objects of classes that are descendants of the Throwable class Copyright © 2007 Addison-Wesley. All rights reserved. 1-24 Classes of Exceptions The Java library includes two subclasses of Throwable : – Error Thrown by the Java interpreter for events such as heap overflow Never handled by user programs – Exception User-defined exceptions are usually subclasses of this Has two predefined subclasses, IOException and RuntimeException (e.g., ArrayIndexOutOfBoundsException and NullPointerException Copyright © 2007 Addison-Wesley. All rights reserved. 1-25 Java Exception Handlers Like those of C++, except every catch requires a named parameter and all parameters must be descendants of Throwable Syntax of try clause is exactly that of C++ Exceptions are thrown with throw, as in C++, but often the throw includes the new operator to create the object, as in: throw new MyException(); Copyright © 2007 Addison-Wesley. All rights reserved. 1-26 Binding Exceptions to Handlers Binding an exception to a handler is simpler in Java than it is in C++ – An exception is bound to the first handler with a parameter is the same class as the thrown object or an ancestor of it An exception can be handled and rethrown by including a throw in the handler (a handler could also throw a different exception) Copyright © 2007 Addison-Wesley. All rights reserved. 1-27 Continuation If no handler is found in the try construct, the search is continued in the nearest enclosing try construct, etc. If no handler is found in the method, the exception is propagated to the method’s caller If no handler is found (all the way to main), the program is terminated To insure that all exceptions are caught, a handler can be included in any try construct that catches all exceptions – Simply use an Exception class parameter – Of course, it must be the last in the try construct Copyright © 2007 Addison-Wesley. All rights reserved. 1-28 Checked and Unchecked Exceptions The Java throws clause is quite different from the throw clause of C++ Exceptions of class Error and RunTimeException and all of their descendants are called unchecked exceptions All other exceptions are called checked exceptions Checked exceptions that may be thrown by a method must be either: – Listed in the throws clause, or – Handled in the method Copyright © 2007 Addison-Wesley. All rights reserved. 1-29 Other Design Choices A method cannot declare more exceptions in its throws clause than the method it overrides A method that calls a method that lists a particular checked exception in its throws clause has three alternatives for dealing with that exception: – Catch and handle the exception – Catch the exception and throw an exception that is listed in its own throws clause – Declare it in its throws clause and do not handle it Copyright © 2007 Addison-Wesley. All rights reserved. 1-30 The finally Clause Can appear at the end of a try construct Form: finally {... } Purpose: To specify code that is to be executed, regardless of what happens in the try construct Copyright © 2007 Addison-Wesley. All rights reserved. 1-31 Example A try construct with a finally clause can be used outside exception handling try { for (index = 0; index < 100; index++) { … if (…) { return; } //** end of if } //** end of try clause finally { … } //** end of try construct Copyright © 2007 Addison-Wesley. All rights reserved. 1-32 Assertions Statements in the program declaring a boolean expression regarding the current state of the computation When evaluated to true nothing happens When evaluated to false an AssertionError exception is thrown Can be disabled during runtime without program modification or recompilation Two forms – assert condition; – assert condition: expression; Copyright © 2007 Addison-Wesley. All rights reserved. 1-33 Evaluation The types of exceptions makes more sense than in the case of C++ The throws clause is better than that of C++ (The throw clause in C++ says little to the programmer) The finally clause is often useful The Java interpreter throws a variety of exceptions that can be handled by user programs Copyright © 2007 Addison-Wesley. All rights reserved. 1-34 Introduction to Event Handling An event is created by an external action such as a user interaction through a GUI The event handler is a segment of code that is called in response to an event Copyright © 2007 Addison-Wesley. All rights reserved. 1-35 Java Swing GUI Components Text box is an object of class JTextField Radio button is an object of class JRadioButton Applet’s display is a frame, a multilayered structure Content pane is one layer, where applets put output GUI components can be placed in a frame Layout manager objects are used to control the placement of components Copyright © 2007 Addison-Wesley. All rights reserved. 1-36 The Java Event Model User interactions with GUI components create events that can be caught by event handlers, called event listeners An event generator tells a listener of an event by sending a message An interface is used to make event- handling methods conform to a standard protocol A class that implements a listener must implement an interface for the listener Copyright © 2007 Addison-Wesley. All rights reserved. 1-37 Event Classes Semantic Event Classes – ActionEvent – ItemEvent – TextEvent Lower-Level Event Classes – ComponentEvent – KeyEvent – MouseEvent – MouseMotionEvent – FocusEvent Copyright © 2007 Addison-Wesley. All rights reserved. 1-38 Summary Ada provides extensive exception-handling facilities with a comprehensive set of built-in exceptions. C++ includes no predefined exceptions Exceptions are bound to handlers by connecting the type of expression in the throw statement to that of the formal parameter of the catch function Java exceptions are similar to C++ exceptions except that a Java exception must be a descendant of the Throwable class. Additionally Java includes a finally clause An event is a notification that something has occurred that requires handling by an event handler Copyright © 2007 Addison-Wesley. All rights reserved. 1-39