Title: C for Java Programmers
1C for Java Programmers
- Lecture 14
- Algorithms, Exceptions C versus Java
2What you might have missed
- We refreshed our knowledge on
- Templates
- The Standard Template Library
- Containers, Algorithms and Iterators
- Vectors
- Lists
- Maps
3End of the Section
- yup. were going to end this section with
- Algorithms
- Exceptions
- Java vs. C A fight to the death
- C 7 Deadly sins
41. Algorithms
- Algorithms act on containers.
- Just include the ltalgorithmgt library.
- 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() ).
5Counting 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 ltboolgt v
- for(i0 ilt10 i)
- if (rand() 2) v.push_back(true)
- else v.push_back(false)
-
- int matches count(v.begin(), v.end(), true)
- cout ltlt matches ltlt elements are true.
sets up a vector of random trues falses
counts the no. of trues
6Reversing a Sequence
- The reverse() algorithm reverses the order of a
range specified by its start and end iterators. - int main()
- vector ltintgt v
- for(i0 ilt10 i) v.push_back(i)
- reverse( v.begin(), v.end() )
Initially v contains 0 1 2 3 4 5 6 7 8 9
Now v contains 9 8 7 6 5 4 3 2 1 0
sequence marked out by two iterators
7for_each
- using for_each we can apply a function to every
single element of our container. - int main()
- vector ltstringgt tubbies
- v.push_back( dipsy )
- v.push_back( lala )
- v.push_back( po
- for_each(tubbies.begin(), tubbies.end(),
toupper) - for_each(tubbies.begin(), tubbies.end(),
display)
OUTPUT DIPSY LALA PO
8Sorting a Sequence
- Sort() is an incredibly useful algorithm that you
can use on any container it too uses a
sequence. - int main()
- vector ltintgt v
- for(i0 ilt10 i)
- if (rand() 2) v.push_back(rand()10)
-
- sort(v.begin(), v.end())
Initially v contains 3 5 2 2 3 7 8 6 1 0
Now v contains 0 1 2 2 3 3 5 6 7 8
92. Exceptions
- The purpose of this section is to explain how to
- 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.
10Motivations 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
you are human and whatever you tell yourself,
coffee and pro-plus wont replace sleep.
11Synchrony
- 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.
12The 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.
13Dividing by ZERO
- Imagine we have a class that stores fractions.
- One of its methods would be used to set the
denominator. - void FractionsetDenominator(int d)
-
- denominator d
-
-
- 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!
14To solve this put in a check
- void FractionsetDenominator(int d)
-
- if (d ! 0)
- Denominator d
-
- else
- cerr ltlt Illegal Denominator ltlt d
- ltlt using 1 instead
- Denominator 1
-
-
-
- An alternative version would use an
exception-handler.
void FractionsetDenominator(int d) try
if (d ! 0) Denominator d else
throw(d) catch(int i) cout ltlt
Illegal Denominator ltlt i ltlt using 1
instead Denominator 1
15Exception Handling Components
Trying
Throwing
Catching
16Catch Handlers
- A catch handler resembles a function definition
- catch (ParameterType ParameterName)
- //Handler Body
-
- A catch handler begins with the keyword catch and
a single-parameter 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.
17Tries, Throws and Catches
-
- void FractionsetDenominator(int d)
-
- try
- if (d ! 0) denominator d
- else throw(d)
-
- catch(int i)
- cout ltlt Illegal Denominator
- cout ltlt i ltlt - using 1 instead
- denominator 1
-
-
18Exception 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.
19Catching DMA Errors
- If you try to use the new operation and the
request cant be satisfied an exception is
generated. - int main()
- int size 0
- try
- while (true)
- char p new char
- size
-
-
- catch(bad_alloc b)
- cout ltlt We ran out of memory after ltlt size
-
bad_alloc is the exception generated but dont
forget to include the ltnewgt library in your code
20Lots 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)
21Try, try and try again
You can do some clever stuff by nesting try
blocks. Diagrammatically this looks something
like
22Nested Try Example
With nested try blocks control is transferred to
the nearest handler with the appropriate type.
- void func()
- try
- string manager
- cin gtgt manager
- if (manager) throw(1)
- Team villa new Team(name)
-
- catch(int i) cout ltlt you must enter a name
-
- int main()
- try func()
- catch( bad_alloc) cout ltlt memory error
-
23Catching any exception
- There is a special syntax that will cover any
throw type - try
- string name
- cin gtgt name
- if (name ) throw(1)
- Tellytubby t new Tellytubby(name)
-
- catch(...)
- cout ltlt 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.
24A 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
-
25Types of Exception
- The exceptions that we have looked at have tended
to be made by us. - However if we include ltexceptiongt library, we get
lots of exception classes that represent errors. - We can use these in the catch statement for
example
bad_alloc - thrown by new when it has a
problem bad_cast - thrown automatically
when a cast fails overflow_error -
Arithmetic overflow. invalid_argument -
Incorrect arg was used in a function call
26Exception Hierarchy
exception
bad_alloc
bad_cast
bad_typeid
bad_exception
iosfailure
logic_error
runtime_error
range_ error
out_of_ range
domain_error
invalid_ argument
overflow_error
underflow_error
27Summary 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-the-ordinary happens from the main logic
of your program. - You can write your own throws or use the ones
provided in the C standard library.
28What we have done
All the Fundamentals Arrays, Variables, Control
Structures, Null Terminated Strings, Functions,
Structs,
C for Java Programmers
Theoretical C Pointers, DMA, Classes,
Input/Output, Inheritance, Templates, STL,
Exceptions
C for C/Java Programmers
Useful C Integrated Development Environments,
Using 3rd Party Libraries, openGL, Artificial
Intelligence.
Some Applied C
29Things 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 - Namespaces
- The Preprocessor
- Virtual Functions
- Abstract Classes
303. 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.
31Data Types and Variables
- 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 ! lt lt gt gt. 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.
32Classes
- 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.
33Objects
- 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.
34Functions
- 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
35Pointers
- 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 -gt 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.
36Inheritance
- 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.
37The 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
38Exercise of the day
- Define an exception for string contains
characters that cannot be sent - Make sure it contains a string with the bad
characters. - Write a function send_message(string s) which
normally displays the string on the standard
output, but which throws an exception as defined
above, if necessary. - Call it from a function prepare_and_send called
by main, catching the exception only in main.