Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
42 views

C++ For Java Programmers

The document provides an overview of algorithms and exceptions in C++. It discusses common algorithms like count, reverse, sort and for_each that can operate on containers. It also covers how exceptions allow programs to handle errors, including throwing, catching and nested exception handling. Different exception types are presented, like bad_alloc from the standard library. The document concludes with a summary of exceptions in C++.

Uploaded by

dipen12
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
42 views

C++ For Java Programmers

The document provides an overview of algorithms and exceptions in C++. It discusses common algorithms like count, reverse, sort and for_each that can operate on containers. It also covers how exceptions allow programs to handle errors, including throwing, catching and nested exception handling. Different exception types are presented, like bad_alloc from the standard library. The document concludes with a summary of exceptions in C++.

Uploaded by

dipen12
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

What you might have missed:

C++ for Java Programmers


Lecture 14:
Algorithms, Exceptions & C++ versus Java We refreshed our knowledge on: Templates The Standard Template Library Containers, Algorithms and Iterators Vectors Lists Maps The Short Answer Test

End of the Section

1. Algorithms
Algorithms act on containers.

yup. were going to end this section with: Just include the <algorithm> library.

Algorithms Exceptions Java vs. C++ : A fight to the death C++ 7 Deadly sins

Algorithms can be applied to any type of container. They often use sequences these are a list of elements defined by a starting and finishing iterators (eg. v.begin() and v.end() ).

Counting the contents


One of the most basic operations you can perform on a sequence is to count its contents - we can use count().
int main() { vector <bool> v;
sets up a vector of random trues & falses

Reversing a Sequence
The reverse() algorithm reverses the order of a range specified by its start and end iterators.
Initially v contains:

for(i=0; i<10; i++) { if (rand() % 2) v.push_back(true); else v.push_back(false); } counts the no. of trues

int main() { vector <int> v;

0123456789

for(i=0; i<10; i++) v.push_back(i); reverse( v.begin(), v.end() ); }


Now v contains: 9876543210

int matches = count(v.begin(), v.end(), true); cout << matches << elements are true.; }

sequence marked out by two iterators

for_each
using for_each we can apply a function to every single element of our container.
int main() { vector <string> tubbies; v.push_back( dipsy ); v.push_back( lala ); v.push_back( po }
OUTPUT: DIPSY LALA PO

Sorting a Sequence
Sort() is an incredibly useful algorithm that you can use on any container it too uses a sequence.
int main() { vector <int> v;
Initially v contains: 3522378610

for(i=0; i<10; i++) { if (rand() % 2) v.push_back(rand()%10); } sort(v.begin(), v.end()); }


Now v contains: 0122335678

for_each(tubbies.begin(), tubbies.end(), toupper); for_each(tubbies.begin(), tubbies.end(), display); }

2. Exceptions
The purpose of this section is to explain how to:

Motivations for Exceptions


They allow abnormal conditions which arise during execution to be detected and handled. For the real geeks this is analogous to setjmp() and longjmp() in C. A library implementer can detect run-time errors when its library is used, but cannot in general handle them. The user of a library in general knows how to handle errors, but cannot detect them very well - your human and whatever you tell yourself coffee and pro-plus wont replace sleep.

detect erroneous conditions to signal such conditions to your program to work out what on earth do with them

The aim is to give you the knowledge to extend your programs to correctly throw and catch exceptions when run-time errors arise. This is crucial in all professional programs. In courseworks handling exceptions =marks.

Synchrony
Exceptions in C++ are synchronous they are used for error handling, such as failures during array bounds checking. Asynchronous exceptions such as timer or keyboard interrupts are not handled directly by the language. Most systems provide some mechanism for handling asynchronous exceptions such as UNIX signals but since these features are system-dependent, they are excluded from C++ itself.

The Exception process


An exception is a program error that occurs during execution it stands for an exceptional situation. If an exception occurs the flow of control can be transferred to an exception-handler code segment. If there is no handler, as you have probably seen many times over, the program terminates. Hence exception handlers makes your code ROBUST.

Dividing by ZERO
Imagine we have a class that stores fractions. One of its methods would be used to set the denominator.
void Fraction::setDenominator(int d) { denominator = d; }

To solve this put in a check


void Fraction::setDenominator(int d) { try { if (d != 0) { if (d != 0) Denominator = d; Denominator = d; else throw(d); } } else { catch(int i) { Illegal Denominator: << d cerr << cout << Illegal Denominator: << i << using 1 instead; << using 1 instead; Denominator = 1; Denominator = 1; } } } }

But if this denominator is set to zero when we try to use the fraction its going to make our program collapse in a heap in the corner as it tries to divide by zero. We need to use an exception-handler!

An alternative version would use an exception-handler.

Exception Handling Components

Catch Handlers
A catch handler resembles a function definition:

Trying

Code that deals with the situations in which exceptions can arise directly or indirectly through function calls is put in a try block

catch (ParameterType ParameterName) { //Handler Body }

Throwing

If an errant situation is detected a throw statement is invoked. This passes information about the error to the exception handler.

A catch handler begins with the keyword catch and a singleparameter list. The type of exception should match a type of exception that can be thrown from the try block. Following this is the catch statement block this is executed if the catch handler is invoked to process an exception.

Catching

Following the try block are the catch-exception handlers. There is typically a catch handler for each possible type of exception in the try block.

Tries, Throws and Catches


First of all a try block tests to see if d is zero in value. If d is zero an exception is thrown The value of this exception is have Because we 0. defined a catch handler that takes an int there is an exception handler for bad denominator void Fraction::setDenominator(int d) { try { if (d != 0) denominator = d; else throw(d); } catch(int i) { cout << Illegal Denominator: ; cout << i << - using 1 instead; denominator = 1; } }

Exception Handling Flexibility


Although this seems excessive for the task at hand, the mechanism is vital for the OO paradigm. For example suppose an error occurred within the function f() that was invoked by a function g() that was invoked by a function h(). Further, to correct the error, suppose that function h() which started the sequence must regain the flow of control. Exception Handling has the flexibility to do this it can unwind the function invocations and allow correction to be made at the source.

Catching DMA Errors


If you try to use the new operation and the request cant be satisfied an exception is generated.
int main() { bad_alloc is the int size = 0; exception generated try { but dont forget to while (true) { include the <new> library in your code char *p = new char; ++size; } } catch(bad_alloc b) { cout << We ran out of memory after: << size; } }

Lots of Throwing and Catching


We can have lots of different throw statements in our try block each with different throw types
try { if ( isupper(ch) ) throw(1); else if ( islower(ch) ) throw(1.1); else if (ch==.) throw(ch); }

Equally we can have more than one catch block the one that matches the throw type will be executed:
catch(int i) { cout << uppercase letters not allowed; } catch(float f) { cout << lowercase letters frowned upon; } catch(char c) { cout << full stops are banned too; }

Try, try and try again


You can do some clever stuff by nesting try blocks. Diagrammatically this looks something like:

Nested Try Example


With nested try blocks control is transferred to the nearest handler with void func() { the appropriate type. try { string manager; cin >> manager; if (manager==) throw(1); Team villa = new Team(name); } catch(int i) { cout << you must enter a name; } }

try {
try {
try {

if a catch is not the right type the flow will go up the nest

catch {

} catch { }

} }

catch {

int main() { try { func(); } catch( bad_alloc) { cout << memory error; } }

Catching any exception


There is a special syntax that will cover any throw type:
try { string name; cin >> name; if (name ==) throw(1); Tellytubby t = new Tellytubby(name); } catch(...) { cout << Im sorry. LALA is dead; } }
The ... ellipsis indicates that the catch handler is there to catch exceptions not caught by the handlers that preceded it.

A Full Exception Check


readFile { try { open the file; determine its size; allocate that much memory; read the file into memory; close the file; } catch (fileOpenFailed) { doSomething; } catch (sizeDeterminationFailed) { doSomething; } catch (memoryAllocationFailed) { doSomething; } catch (readFailed) { doSomething; } catch (fileCloseFailed) { doSomething; } }

Types of Exception
The exceptions that we have looked at have tended to be made by us. However if we include <exception> library, we get lots of exception classes that represent errors. We can use these in the catch statement for example:
bad_alloc bad_cast overflow_error invalid_argument - thrown by new when it has a problem - thrown automatically when a cast fails - Arithmetic overflow. - Incorrect arg was used in a function call

Exception Hierarchy
exception

bad_alloc

bad_cast

bad_exception

bad_typeid

ios::failure

logic_error

runtime_error

domain_ error

invalid_ argument

out_of_ range

overflow _error

underflow _error

range_ error

Summary of Exceptions
exceptions don't spare you the effort of handling errors. They do provide the means to separate all the grungy details of what to do when something out-of-theordinary happens from the main logic of your program. You can write your own throws or use the ones provided in the C++ standard library.

What we have done


All the Fundamentals : Arrays, Variables, Control Structures, Null Terminated Strings, Theoretical C++ : Functions, Structs, Pointers, DMA, Classes, Input/Output, Inheritance, Templates, STL, Useful C++ Exceptions Integrated Development Environments, Using 3rd Party Libraries, openGL, Artificial Intelligence. C++ for C/Java Programmers C for Java Programmers

Some Applied C++

Things that we havent done


The following are some topics that we havent had chance to look at. If you really want to have a wide knowledge of C++ these are worth a peek:
1. 2. 3. 4.

3. C++ vs. Java :: fight to the death


C++ has many features in common with Java. Nevertheless, C++ is a much more complex language than Java. The biggest potential stumbling block is speed: interpreted Java runs in the range of 20 times slower than C. there are just-in-time compilers appearing more recently that offer significant speed-ups. It is not inconceivable that full native compilers will appear. However to compensate Java is more robust.

Namespaces The Preprocessor Virtual Functions Abstract Classes

Data Types and Variables


1.

Classes
1.

Data types almost identical C++ has extra short and unsigned types. The Boolean type is called bool in C++. C++ strings store ASCII characters, not Unicode characters To compare strings, C++ uses == != < <= > >=. The last four operators perform lexicographic comparison. This is actually more convenient than the use of equals and compareTo in Java. The C++ compiler does not check whether all local variables are initalized before they are read.

In C++, there are public and private sections, started by the keywords public and private. In Java, each individual item must be tagged with public or private - this is a pain. The class definition only contains the declarations of the methods. The actual implementations are listed separately in C++. Accessor methods are tagged with the keyword const in Java. There is a semicolon at the end of the class in C++.

2. 3.

2.

4.

3.

5.

4.

Objects
The major difference between Java and C++ is the behaviour of object variables. In C++, object variables hold values, not object references. The new operator is never used when constructing objects in C++. You simply supply the construction parameters after the variable name. This is often preferable, but when modifying an object in a function, you must remember to use call by reference in C++.

Functions
In Java, every function must be an instance method or a static function of a class. C++ supports instance methods and static functions of classes, but it also permits global functions. Java does not support default arguments Java does not support inline functions. Java does have built in multithreading support

Pointers
C++ pointers are very much like Java object variables. There is, however, an essential syntactical difference. You must apply the * operator to access the object to which a pointer points. If you do not initialise a pointer, or if the pointer is NULL or refers to an object that no longer exists, then it is an error to apply the * or -> operator. Unfortunately, the C++ runtime system does not check against these errors. Java has a garbage collector - In C++, it is the responsibility of the programmer to manage memory.

Inheritance
The basic syntax for inheritance is similar in C++ and Java. In C++, you use : public instead of extends to denote inheritance. By default, functions are not dynamically bound in C++. If you want which dynamic binding for a particular function, you must declare it as virtual.

The hidden irony of all these comparisons?

I teach C++ but the slides are displayed on the web page using a java applet.

The Seven Deadly Sins

7. Using Uninitialised Variables 6. Dereferencing a Null Pointer 5. Forgetting Copy Constructors 4. Memory Leaks 3. Out of Bounds Array access 2. Using = instead of == 1. forcing someone to use the g++ compiler

Have a good weekend

You might also like