Comprog Study Guide
Comprog Study Guide
In almost every facet of our daily life, we live in close contact with
computers. Whether we realize it or not, we use them as a matter of routine. They
come in many sizes and shapes and do many useful things for us. If you own a
digital watch, you have a computer that tells you what time it is. Your car probably
has several computers that perform many different functions, such as injecting fuel
into its engine, indicating that door is ajar, telling you how many more miles you
can drive on the remaining fuel, and so on. If your telephone has a redial button, it
has a computer in it that remembers the last number you dialed. Your school has
many microcomputers, workstations, and perhaps even mainframes. You probably
own a personal computer at home. The examples of computers and computer
applications around us are nearly endless. So, what is Computer?
COMPUTER
• It is an electronic device that can input and store a set of instructions
designed to perform a specific task, input and store data, process the stored
data according to the instructions, and produce output to be relayed to its
user.
SPECIAL-PURPOSE COMPUTER
• It is a computer designed for a particular function, executing the same
stored set of instructions whenever requested.
GENERAL-PURPOSE COMPUTER
• It is a computer that can be used for solving many different types of
problems.
1
Computer Programming
PROGRAM COMPUTE
M R
DATA OUTPUT
DATA INPUT
STRUCTURE
Area = (1/2)*base*h;
ALGORITHM
• It comes from the word "algorism", means the first Arab numerical.
• It is a finite set of instructions that specify a sequence of operations to be
carried out in order to solve a specific problem.
• It is a recipe for solving the problem.
1. Input
• It must have input. It is conceivable that an algorithm may have no
input.
2. Output
• It must produce at least one output. An algorithm that does not
produce anything is worthless.
2
Computer Programming
3. Unambiguousness
• It must be unambiguous. In most cases, we develop an algorithm so
that it can be translated into a computer program to be executed by
computer. Computers cannot cope with ambiguities. Therefore, every
step in an algorithm must be clear as to what it is supposed to do, and
how many times it is expected to be executed.
4. Generality
• It must have generality.
5. Correctness
• It must be correct and must solve the problem for which it is
designed.
6. Finiteness
• It must execute its steps and terminate in finite time. An algorithm
that never terminates is unacceptable.
7. Efficiency
• It must be efficient. An algorithm that is designed for a specific
computer is not worth much if it takes days to solve a relatively simple
problem or if it requires more memory than what is available on that
computer.
DATA STRUCTURE
• It is an organized collection of values that may be used for data together
with a set of operations that may be done on that data.
Characteristics
1. Type of items
2. Relationship among its items
Categories
1. Scalar or Elementary Types
• These are data whose values are directly supported in the hardware of
the computer.
2. Structure Type
• It is a group of scalar
3. Abstract Type
• The type of data that are defined by the programmers.
3
Computer Programming
PROGRAM
• It is a sequence of instructions for a computer.
• This can be as simple as a DOS batch file or a lotus 1-2-3 Macro, or as
complex as a spreadsheet program written in C or assembly language.
TYPES OF PROGRAMS
A. According to Conversion
1. COMPILER
• It is a program which permanently translates the source code into
machine language and gives you a complete stand-alone program.
• Example: COBOL, TURBO C, TURBO PASCAL etc.
2. INTERPRETER
• It is a program which translates the source code one line at a time
each time the program is run.
• Example: GWBASIC/BASIC etc.
PROGRAMMING LANGUAGE
• A Programming Language as the means by which tell the computer
what you want done.
• Languages differ in many ways. Some are more computer-like; others
more English-like; some are for numeric processing; while others are
better for text processing; some are hardware based, while others are
structured or based on objects. But all programming languages have
the roots in the binary numbering system.
4
Computer Programming
Example:
a. FORTRAN (FORmula TRANslation)
• It is used for engineering and scientific applications or numeric
processing
b. COBOL (COmmon Business Oriented Language)
• It is used for Business data transaction processing and reporting.
c. BASIC (Beginner’s All-purpose Symbolic Instruction Code)
• It is a simple language intended for student use in school-work.
d. LISP (LISt Processing)
• It is used in many educational setting for artificial intelligence
applications.
e. C / C++
• C is used for writing system software
• C++ is an extension of C that support object-oriented
programming.
f. PASCAL
• It is used for teaching students to program in a careful, disciplined
way.
g. MODULA-2
h. VISUAL BASIC
BRIEF HISTORY
C LANGUAGE
The C programming language was developed in the early 1970s at AT&T
Bell Laboratories in New Jersey by a researcher named Dennis Ritchie. Although C
was originally developed with systems programming in mind (the UNIX operating
system is written in C), it now finds application to development of numerical and
engineering software as well.
The predecessor to C was the language B designed by Ken Thompson in
1970 for the first UNIX system on a DEC PHP 7 at Bell Laboratories. B was influenced
by the language BCBL developed by Martin Richards in the 1960s.
5
Computer Programming
The C programming language is becoming the standard language for
developing both system and application programs. It is a popular “high level”
language that allows software to be used on many machines without being
rewritten.
C++ LANGUAGE
C++ was invented by Bjarne Stroustrup in 1979, at Bell Laboratories in
Murray Hill, New Jersey. He initially called the new language “C with Classes.”
However, in 1983 the name was changed to C++.
C# LANGUAGE
6
Computer Programming
KEY FEATURES OF C LANGUAGE
1. Operating system portability
C is a language that was designed in such a way that it would be
easy to implement a translator for it on various operating systems.
The result is a language that is available on virtually every
operating system in existence. Therefore, a version of an existing
program written in standard C can easily be transported to another
operating system.
APPLICATIONS OF C LANGUAGE
1. Database Applications
2. User interfaces
3. Networking Applications
4. Graphics
5. Operating system
6. Business Applications
7. Engineering and real-time applications.
7
Computer Programming
A. Program Identification
/* AUTHOR
DATE
PROGRAM DESCRIPTION
*/
B. Compiler Directives:
#include
#define
E. Main Program
8
Computer Programming
Simplified format of a C/C++ Program
/* INTRODUCTORY COMMENTS
FILE NAME, PROGRAMMER
WHEN WRITTEN OR MODIFIED
PROGRAM DESCRIPTION */
Preproccessor directives
void main()
{
constant declarations
variable declarations
executable statements
{
}
}
Note:
• It makes complex programs much easier to interpret if, as above, closing
braces } are aligned with the corresponding opening brace {.
• Also additional spaces, new lines etc. can also be used to make programs
more readable. The important thing is to adopt one of the standard
conventions and stick to it consistently.
Example:
Preprocessor: performs
preliminary operations on
files before they are passed
to the compiler.
LIBRARY
It is a collection of useful functions and symbols that may be accessed by a
program.
10
Computer Programming
COMMENTS
A program comment is like a parenthetical remark in a sentence – it is
intended to make the program easier to understand by describing its
purpose.
Comments are also used to describe the use of identifiers and the
purposes of each program step.
Comments are an important part of the documentation of a program
because they help others read and understand the program.
The compiler ignores comments; they are not translated into machine
language.
SYNTAX:
// COMMENT
/* COMMENT */
EXAMPLE
// This is a comment
/* and so
is this */
INTERPRETATION:
// can be used only when comment fits on a single line or when the
remainder of a line is a comment.
/* */ can stand alone or can be embedded in the of the statement. A
comment that begins with /* may extend over any number of lines until it
closes with */.
PREPROCESSOR
The preprocessor is a program that runs prior to compilation and
potentially modifies a source code file.
It may add code in response to the #include directive, conditionally
include code in response to #if, #ifdef, #ifndef directives or define
constants using the #define directive.
PREPROCESSOR DIRECTIVES
The preprocessor directives are commands that give instructions to the
C preprocessor, whose job is to modify the text of a C program before it is
compiled.
A preprocessor directive begins with a number symbol (#) as its first
nonblank character.
11
Computer Programming
The two most common directives are #include and #define.
#include DIRECTIVE
The #include directive instructs the preprocessor to read and include a file
into a source code file.
The file name is typically enclosed with < and > if the file is a system
provided file, or in quotes if the file is user provided.
Syntax:
#include <standard header file>
or
#include “user-defined header file”
Examples:
#include <stdio.h>
#include <math.h>
#include <iostream.h>
#include “myserial.h”
#include “myhfiles.h”
Interpretation:
#include directives tell the preprocessor where to find the meanings of
standard identifiers used in the program. These meaning are collected in
files called standard header files.
The header file stdio.h contains information about standard input and
output function such as scanf and printf.
Descriptions of common mathematical functions are found in the header file
math.h
The header file iostream.h is required in order to be able to use the stream
input/output facilities provided by cin, cout and endl.
#define Directive
It is used for Creating Constant Macros.
CONSTANT MACRO
A name that is replaced by a particular constant value before the program
is sent to the compiler.
Syntax:
#define NAME value
or
#define FUNCTION_NAME (expression)
Examples:
#define MILES_PER_KM 0.62137
#define PI 3.1416
#define MAX_LENGTH 100
#define p printf
12
Computer Programming
#define MAX(A,B) ((A)>(B)?(A):(B))
#define CUBE(A) (A)*(A)*(A)
#define ADD(A) ((A)+(A))
#define SUM(A,B) ((A)+(B))
Max(1,3) = 3
#define sw1 (PAIN&0x80)
Interpretation:
The C/C++ preprocessor is notified that it is to replace each use of the
identifier NAME by value.
C/C++ program statements cannot change the value associated with
NAME.
FUNCTION MAIN
The heading main() marks the beginning of the main function where
program execution begins.
Every C/C++ program has a main function.
The remaining lines of the program form the body of the function which
enclosed in braces {,}.
A function body has two parts: declarations and executable statements.
DECLARATION
A declaration is used to specify the name and type of an object to the
compiler.
EXECUTABLE STATEMENTS
Program lines that are converted to machine language instructions and
executed by the computer.
SYNTAX:
[return_data_type] main([data_type])
{
function body
}
EXAMPLE:
int main(void)
{
printf(“ University of the East\n”);
return(1);
}
13
Computer Programming
void main(void)
{
printf(“ University of the East\n”);
}
void main()
{
printf(“ University of the East\n”);
}
DATA TYPES
DATA TYPE
void 0 array
char 1 struct
int 2 union
float 4
double 8
14
Computer Programming
QUALIFIERS
Qualifiers can be applied to the fundamental types.
The four Qualifiers are:
1. signed +-
2. unsigned+
3. short - same
4. long +2
15
Computer Programming
THE BASIC LANGUAGE ELEMENTS ARE:
1. Reserved words/ Keywords
2. Identifiers
3. Constants
4. Separators
5. Operators
RESERVED WORD/KEYWORD
Reserved word or keyword is a word that has special meaning in C/C++.
It cannot be redefined or used in other contexts. For instance, it cannot
be used as variable name.
These words always appear in lowercase
The keywords in the C++ language are:
asm auto bool break
while
16
Computer Programming
IDENTIFIERS
The names you give to constants, data types, variables, and functions.
Two rules must be kept in mind when naming identifiers:
The case of alphabetic characters is significant.
Up to 31 characters can be used and will be considered significant.
STANDARD IDENTIFIER
A word having special meaning but one that a programmer may redefine
(but redefinition is not recommended)
The standard identifiers printf and scanf are names of operations defined
in the standard input/output library (stdio.h).
Valid identifiers
Voltage_1 Ampere2 Karen Length5 RESISTANCE
OUTPUT_PER_INPUT R I Mario
Michael_Jordan23 LJ
Invalid identifiers:
2voltage /* begins with a digit */
double /* reserved word */
THREE*ONE /* character * not allowed */
Shakey’s /* character ‘ not allowed */
Tip:
Some programmers use an underscore in variable names to separate parts
of the name, such as voltage_output.
Others prefer a "capital style" notation, such as voltageOutput to
separate parts of the name.
NEVER use UPPERCASE for every letter in a variable name, because
uppercase names are reserved for constant.
The best naming convention is to choose a variable name that will tell the
reader of the program what the variable represents.
17
Computer Programming
CONSTANTS
Constants are values that cannot be changed.
1. Integer Constant
An integer constant is consisting of a sequence of digits, beginning
with unary minus for negatives or an optional unary plus for
positives.
Integer constants may be written in the following forms:
Decimal form without a prefix.
▪ Ex. 15
Hexadecimal form with 0x or 0X prefix
▪ Ex. 0xF
Octal form with 0 prefix
▪ Ex. 017
An integer constant may be suffixed by the letter
unsigned integer constants can have the suffix u or U
▪ Ex. 123U
long integer constants can have the suffix l or L
▪ Ex. 123L
unsigned long integer constants can have the suffix ul or UL
▪ Ex. 123UL
2. Floating-point Constants
Floating-point constants are stored, on most computers, in a different
form from that of integers.
A floating-point value represents a real number.
The constant is of the type double unless a suffix is used to alter the
range and precision.
The suffixes are:
The letter “F” or “f”, which makes it a float.
▪ Ex. 1.234F
The letter “L” or “l” to make a long double.
▪ Ex. 1.234L
18
Computer Programming
There are two written representations:
1. f Notation
It is consisting of integer part, decimal point, fractional part,
optionally with one part omitted.
For example:
0.86 2.0 -0.005
2. e Notation
The letter e or E is used to separate the mantissa from the
exponent of the power of 10.
For example:
1.38E-23 or 1.38 x 10-23
1.5E1, 1.5e1, 15E0, .15e2, 150E-1 are all the same value.
Note:
Read E as “ times 10 to the power of…”
The exponent is of the integer type.
3. Character Constants
Character constants can be printable (like 0 to 9 and a to z) or non-
printable characters (such as new line, carriage return, or tab).
Printable character constants may be enclosed in single quotation marks
(such as ‘s’).
The value of a character constant with only one character is the numeric
value of the character in the machine’s character set at the execution
time.
Note:
The code used to represent characters is a subset of the American Standard
Code for Information Interchange (ASCII)-the most common 7-bit character
code. IECEP – 0x49,0x45, 0x43,0x45, 0x50
A=0x40 +1 = 0x41, E = 0x40+5 =0x45, M = 0x40+0x0D = 0x4D, 64+13
=77
A= 65, 64+1 = 65
a = A+space = 65+32 = 97
0=48
C uses an escape convention consisting of a character constant that
begins with a backslash and single lower case letter code for the
common control codes, and the further convention of either an octal or
hexadecimal number for any arbitrary code.
19
Computer Programming
The single letter codes or escape sequences are:
Newline \n Backslash \\
Horizontal tab \t Question mark \?
Vertical tab \v Single quote \’
Backspace \b Double quote \”
Carriage return \r Octal number \000
Form-feed \f Hex number \xff
Audible alert/bell \a
\‘a\’ – ‘a’
ASCII TABLE AND DESCRIPTION
20
Computer Programming
EXTENDED ASCII
ñÑ╢╔═╦═╗ñÑñÑαßΓ
Char. Decimal Pair Hex Pair Char. Decimal Pair Hex Pair
ALT-A (00,30) (0x00,0x1e) ALT-B (00,48) (0x00,0x30)
ALT-C (00,46) (0x00,0x2e) ALT-D (00,32) (0x00,0x20)
ALT-E (00,18) (0x00,0x12) ALT-F (00,33) (0x00,0x21)
21
Computer Programming
4. Strings constants
A string constant is a one-dimensional array, or vector, of character
codes and has written form of a sequence of characters enclosed in a
pair of double quotation marks.
This requires the character code escape of \” for double quote itself,
should one be needed in a string.
Additionally, the escape sequences from the character constant codes
are supported.
It is possible to have an empty string, which is simply two double-
quote characters.
For example:
The string “ Nancy Jowel “ = Nancy Jowel
‘N’ ‘a’ ‘n’ ‘n’ ‘y’ ‘ ’ ‘J’ ‘o’ ‘w’ ‘e’ ‘l’ ‘\0’
This shows how the string “Nancy Jowel” is stored in the memory.
The value of the string constant is an address of where the characters
making up the string are stored. The compiler automatically places a
NUL character ‘\0’ at the end of the string in order for it to be possible
to find the end of the string.
Each memory byte contains the binary code for the character. The
value of the string is the address of the first byte.
The shortest string (the empty string) is “ “, which has just the NUL
character (‘\0’).
5. Enumeration constants
Enumerations are unique types with values ranging over a set of named
constants called enumerators.
The identifiers in an enumerator list are declared as constants of type
int, and may appear wherever constants are required.
The reserved word enum is used to assign sequential integer constant
values to a list of identifier.
Example 1:
enum Boolean { FALSE , TRUE };
22
Computer Programming
In this case the constant names will be automatically assigned values
starting at 0, so that FALSE is 0 and TRUE is 1.
Example 2:
enum LETTER { A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P };
The name A is assigned a constant value of 0, B of 1, C of 2, and so on.
One of the advantages of this method over that of using #define is that
variables of this may be able to issue warnings when inappropriate types
are assigned; the other advantage is that the values are automatically
assigned.
SEPARATORS
Separators are used to separate adjacent characters and to enhance
readability such as blanks, tabs and newlines.
OPERATORS
One of the characteristics of C is that it has a small set of keyword and a
rich set of operators.
Often, the operators have more than one use.
The specific function of an operator depends on the context in which it is
used.
Some examples are:
The plus ‘+’ character:
a+b ++a a+=b
In this example, the + character is used as an addition operation in
the first instance, as the pre-increment operator in the second, and
as an assignment operator in the third.
VARIABLE DECLARATIONS
Variable declarations are statements that communicate to the compiler the
names of variables in the program and the kind of information stored in
each variable.
All variables must be declared before they can be used.
Declaring Variables
1. Choose the "type" you need.
2. Decide upon a name for the variable.
3. Use the following format (syntax) for a declaration statement:
datatype variable_identifier;
4. You may declare more than one variable of the same type by separating the
variable names with commas.
int Age;
float Weight, Height;
5. You can initialize a variable (place a value into the variable location) in a
declaration statement.
24
Computer Programming
Example:
1. For integer
int Age, Quantity;
int Age = 12, Quantity =100;
long int Quantity;
2. For floating-point and double
float Height, Weight, Grade;
float Height = 5.9;
double Price = 1000000.00;
3. For character
char MyInitial, MiddleInitial;
char MyInitial = ‘M’, MiddleInitial = ‘C’;
4. For string
char Name[20]; // Maximum of 20 characters
char Name[] = “Nancy Jowel McDonie”;
5. For array of integer and array of float
int Row[10], Column[12];
float buffer[6];
int Row[5] = { 1, 4, 5, 6,10 };
// where Row[0] = 1;Row[1] = 4;Row[2]=5;
Row[3] = 6;Row[4] = 10;
SCOPE OF VARIABLES
1. Global variable
A global or external variable is a memory space that is allocated by the
compiler and can be accessed by all the functions in a program
(unlimited scope).
It can be modified by any function and will remain its value to be used
by other functions.
It is declared outside of any function, before the program begins, above
the main() function.
2. Local variable
Local variables are memory spaces allocated by the function when the
function is entered, typically on the program stack.
These variables are not accessible from other functions, meaning that
their scope is limited to the functions in which they are declared.
The local variable declaration can be used in multiple functions without
conflict, because the compiler sees each of these variables as being part
of that function only.
It is declared inside the function after its opening curly bracket.
Note: If a local variable name has the same name with a global variable, the local
overwrites the global, but when function terminates, the global name is retained.
25
Computer Programming
CONSTANT
It cannot be changed within a program.
CONSTANT DECLARATION
Using const you can define an identifier whose values never change.
You MUST assign an initial value into a constant when it is declared.
If you do not place this initial value, C/C++ will not allow you to assign a
value at a later time.
Syntax:
Example:
const int AGE_LIMIT = 21; //this value cannot be changed
const float PI = 3.14159;
THE SEVEN BASIC ELEMENTS OF PROGRAMMING
1. Input
Input means reading values from the keyboard, from a disk, or
from an I/O port.
2. Output
Output means writing information to the standard output
(stdout), to a disk, or to an I/O port.
3. Data types
Data types are constants, variables, and structures that contain
numbers (integer and real), text (characters and strings), or
addresses (of variables and structures).
4. Operations
Operations assign one value to another, combine values (add,
divide, etc.), and compares values (equal, not equal, etc).
5. Conditional execution
Conditional execution means that your program executes a set
of instructions only if a specified condition is true (and skips
them if it is false).
6. Loops(iteration)
Loops execute a set of instructions some fixed number of times
or while some condition is true.
7. Subroutines
Subroutines are separately named sets of instructions that can
be executed anywhere in the program just by a reference to the
name.
26
Computer Programming
STANDARD INPUT/ OUTPUT FUNCTIONS
FUNCTION CALL
In C, it is used to call or activate a function.
Syntax of function:
FUNCTION ARGUMENT
Enclosed in parentheses following the function name; provides
information needed by the function.
INPUT OPERATION
It is an instruction that copies data from an input device into memory.
SYNTAX:
scanf(format_string, input_list);
EXAMPLE:
scanf(“%c”,&MiddleInitial);
scanf(“%f”,&Distance);
INTERPRETATION:
The scanf function copies into memory data typed at the
keyboard by the program user during program execution. The
format string is a quoted string of place holders, one
placeholder for each variable in the input_list. Each int,
double, or char variable in the input_list is preceded by an
ampersand(&).
OUTPUT OPERATION
It is an instruction that displays information stored in a memory.
INFORMATION TO THE STANDARD OUTPUT
printf Function
sends formatted output to stdout
27
Computer Programming
SYNTAX:
printf(format_string, print_list);
printf(format_string);
EXAMPLES:
printf(“I am %d years old, and my gpa is
%f\n”,age,gpa);
printf(“University of the East”);
INTERPRETATION:
The printf function displays the value of its formal string alter
substituting in left-to-right order the values of the expressions in the print
list for their placeholders in the format string and after replacing escape
sequence such as \n by their meanings.
Format string
A string of characters enclosed in quotes(“), which specifies the
form of the output line.
Print list
The variables or expressions whose values are displayed.
Placeholders
Symbols beginning with% in a format string that indicate where
to display each output value.
Placeholder Variable type Function use
%d , %i int, signed int or decimal form printf/scanf
%hd short int, or signed short int printf/scanf
%ld long int or signed long int printf/scanf
%u unsigned int or unsigned short int printf/scanf
%lu unsigned long int printf/scanf
%f float or double printf/scanf
%e, %E float( using e or E notation) printf/scanf
%g,%G assigned decimal digit in either e/E printf
form or f form whichever is shorter.
%lf, float or double scanf
%Lf, %Le long double printf/scanf
%c char printf/scantf
%s String printf/scanf
%o Octal printf/scanf
%x,%X Hexadecimal printf/scanf
28
Computer Programming
29
Computer Programming
C++ EXCEPTION HANDLING
Exceptions provide a way to transfer control from one part of a program to another.
C++ exception handling is built upon three keywords: try, catch, and throw.
try: A try block identifies a block of code for which particular exceptions will
be activated. It's followed by one or more catch blocks.
try
{
// protected code
}catch( ExceptionName e1 )
{
// catch block
}catch( ExceptionName e2 )
{
// catch block
}catch( ExceptionName eN )
{
// catch block
}
You can list down multiple catch statements to catch different type of exceptions in
case your try block raises more than one exception in different situations.
30
Computer Programming
Throwing Exceptions:
Exceptions can be thrown anywhere within a code block using throw statements.
The operand of the throw statements determines a type for the exception and can
be any expression and the type of the result of the expression determines the type
of exception thrown.
Catching Exceptions:
The catch block following the try block catches any exception. You can specify
what type of exception you want to catch and this is determined by the exception
declaration that appears in parentheses following the keyword catch.
try
{
// protected code
}catch( ExceptionName e )
{
// code to handle ExceptionName exception
}
Above code will catch an exception of ExceptionName type. If you want to specify
that a catch block should handle any type of exception that is thrown in a try block,
you must put an ellipsis, ..., between the parentheses enclosing the exception
declaration as follows:
try
{
// protected code
}catch(…)
{
// code to handle ANY exception
}
31
Computer Programming
The following is an example, which throws a division by zero exception and we catch
it in catch block.
#include <iostream>
using namespace std;
double division(int a, int b)
{
if(b == 0)
{
throw "Division by zero condition!";
}
return (a/b);
}
int main()
{
int x = 50;
int y = 0;
double z = 0;
try {
z = division(x, y);
cout << z << endl;
}catch (const char* msg) {
cerr << msg << endl;
}
return 0;
}
Because we are raising an exception of type const char*, so while catching this
exception, we have to use const char* in catch block. If we compile and run above
code, this would produce the following result:
32
Computer Programming
C++ Standard Exceptions:
C++ provides a list of standard exceptions defined in <exception> which we can
use in our programs. These are arranged in a parent-child class hierarchy shown
below:
33
Computer Programming
Here is the small description of each exception mentioned in the above hierarchy −
Sr.No Exception & Description
1 std::exception
An exception and parent class of all the standard C++ exceptions.
2 std::bad_alloc
This can be thrown by new.
3 std::bad_cast
This can be thrown by dynamic_cast.
4 std::bad_exception
This is useful device to handle unexpected exceptions in a C++ program.
5 std::bad_typeid
This can be thrown by typeid.
6 std::logic_error
An exception that theoretically can be detected by reading the code.
7 std::domain_error
This is an exception thrown when a mathematically invalid domain is
used.
8 std::invalid_argument
This is thrown due to invalid arguments.
9 std::length_error
This is thrown when a too big std::string is created.
10 std::out_of_range
This can be thrown by the 'at' method, for example a std::vector and
std::bitset<>::operator[]().
11 std::runtime_error
An exception that theoretically cannot be detected by reading the code.
12 std::overflow_error
This is thrown if a mathematical overflow occurs.
34
Computer Programming
13 std::range_error
This is occurred when you try to store a value which is out of range.
14 std::underflow_error
This is thrown if a mathematical underflow occurs.
Define New Exceptions
You can define your own exceptions by inheriting and overriding exception class
functionality. Following is the example, which shows how you can use std::exception
class to implement your own exception in standard way −
#include <iostream>
#include <exception>
using namespace std;
int main() {
try {
throw MyException();
} catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
//Other errors
}
}
This would produce the following result –
MyException caught
C++ Exception
Here, what() is a public method provided by exception class and it has been
overridden by all the child exception classes. This returns the cause of an exception.
35
Computer Programming
36