Open Means Open Means

EXCEPTION HANDLING IN CPP

No comments on “EXCEPTION HANDLING IN CPP”

 

EXCEPTION HANDLING


Introduction

 

An exception is an indication of a problem that occurs during a program's execution. The name "exception" implies that the problem occurs infrequently if the "rule" is that a statement normally executes correctly, then  the "exception to the rule" is that a problem occurs. Exception handling enables programmers to create applications that can resolve (or handle) exceptions. In many cases, handling an exception allows a program to continue executing as if no problem had been encountered. A more severe problem could prevent a program from continuing normal execution, instead requiring the program to notify the user of the problem before terminating in a controlled manner. The features presented in this chapter enable programmers to write robust and fault-tolerant programs that are able to deal with problems that may arise and continue executing or terminate gracefully.

 

  • Exception handling helps improve a program's fault tolerance.
  • Exception handling provides a standard mechanism for processing errors. This is especially important when working on a project with a large team of programmers.

 

Exception-Handling Overview


Program logic frequently tests conditions that determine how program execution proceeds. Consider the following pseudocode:

 

Perform a task

If the preceding task did not execute correctly

Perform error processing

Perform next task

If the preceding task did not execute correctly

Perform error processing

...

 

In this pseudocode, we begin by performing a task. We then test whether that task executed correctly. If not, we perform error processing. Otherwise, we continue with the next task. Although this form of error handling works, intermixing program logic with error-handling logic can make the program difficult to read, modify, maintain and debug specially in large applications.

 

  • If the potential problems occur infrequently, intermixing program logic and error-handling logic can degrade a program's performance, because the program must (potentially frequently) perform tests to determine whether the task executed correctly and the next task can be performed.

 

Exception handling enables the programmer to remove error-handling code from the "main line" of the program's execution, which improves program clarity and enhances modifiability. Programmers can decide to handle any exceptions they choose all exceptions, all exceptions of a certain type or all exceptions of a group of related types (e.g., exception types that belong to an inheritance hierarchy). Such flexibility reduces the likelihood that errors will be overlooked and thereby makes a program more robust.

With programming languages that do not support exception handling, programmers often delay writing error-processing code or sometimes forget to include it. This results in less robust software products. C++ enables the programmer to deal with exception handling easily from the inception of a project.

 

 

Example 1: Divide by Zero

Let us consider a simple example of exception handling . The purpose of this example is to prevent a common arithmetic problemdivision by zero. In C++, division by zero using integer arithmetic typically causes a program to terminate prematurely. In floating-point arithmetic, division by zero is allowedit results in positive or negative infinity, which is displayed as INF or -INF.

 

 

// Class DivideByZeroException definition.

#include // stdexcept header file contains runtime_error

using std::runtime_error; // standard C++ library class runtime_error

// DivideByZeroException objects should be thrown by functions

// upon detecting division-by-zero exceptions

class DivideByZeroException : public runtime_error

{

public:

// constructor specifies default error message

DivideByZeroException::DivideByZeroException()

: runtime_error( "attempted to divide by zero" ) {}

}; // end class DivideByZeroException

 

 

 

Exception-handling example :2  that throws exceptions

 

 

// A simple exception-handling example that checks for

// divide-by-zero exceptions.

#include

using std::cin;

using std::cout;

using std::endl;

#include "DivideByZeroException.h" // DivideByZeroException class

// perform division and throw DivideByZeroException object if

// divide-by-zero exception occurs

double quotient( int numerator, int denominator )

{

// throw DivideByZeroException if trying to divide by zero

if ( denominator == 0 )

throw DivideByZeroException(); // terminate function

// return division result

return static_cast( numerator ) / denominator;

} // end function quotient

int main()

{

int number1; // user-specified numerator

int number2; // user-specified denominator

double result; // result of division

cout << "Enter two integers (end-of-file to end): ";

// enable user to enter two integers to divide

while ( cin >> number1 >> number2 )

{

// try block contains code that might throw exception       // and code that should not execute if an exception occurs

try

{

result = quotient( number1, number2 );

cout << "The quotient is: " << result << endl;

} // end try

// exception handler handles a divide-by-zero exception

catch ( DivideByZeroException ÷ByZeroException )

{

cout << "Exception occurred: "

<< divideByZeroException.what() << endl;

} // end catch

cout << "\nEnter two integers (end-of-file to end): ";

} // end while

 

cout << endl;

return 0; // terminate normally

} // end main

 

 

 

OUTPUT :


Enter two integers (end-of-file to end): 100 7

The quotient is: 14.2857

Enter two integers (end-of-file to end): 100 0

Exception occurred: attempted to divide by zero

Enter two integers (end-of-file to end): ^Z

 

 

In this example, we define a function named quotient that receives two integers input by the user and divides its first int parameter by its second int parameter. Before performing the division, the function casts the first int parameter's value to type double. Then, the second int parameter's value is promoted to type double for the calculation. So function quotient actually performs the division using two double values and returns a double result.

Although division by zero is allowed in floating-point arithmetic, for the purpose of this example, we treat any attempt to divide by zero as an error. Thus, function quotient tests its second parameter to ensure that it is not zero before allowing the division to proceed. If the second parameter is zero, the function uses an exception to indicate to the caller that a problem occurred. The caller (main in this example) can then process this exception and allow the user to type two new values before calling function quotient again. In this way, the program can continue to execute even after an improper value is entered, thus making the program more robust.

The example consists of two filesDivideByZeroException.h (EXAMPLE 1) defines an exception class that represents the type of the problem that might occur in the example, and (EXAMPLE 2) defines the quotient function and the main function that calls it. Function main contains the code that demonstrates exception handling.

 

 

 

DEVELOPING A “C PROGRAM”

No comments on “DEVELOPING A “C PROGRAM””

The  program development process includes three important stages,  namely, program design, program coding & program testing.  All three stages contribute to the production of  high quality programs. Here we shall discus about program coding .

      PROGRAM  CODING :

          Developed algorithm must be translated into a set of instructions that a computer can understand. The major emphasis in coding should be simply and clarity. A program written by one may have to be read by others later. Therefore, it should be simplicity and readable & simple to understand. Complex logic and tricky coding should be avoided. The elements of  style included internal documentation, construction of statements, generality of program, and input/output formats .

 Internal Documentation:

          Documentation refer to the details that describe a program. Some  details may be built-in as an internal part of the program. These are known as internal documentation.

 The important aspects of  internal documentation are, selection of meaningful variable names and the use of comments. Selection of meaningful names is crucial for understanding the program.  For example

                   area = breadth*length

Is more meaningful than – a = b*l;

 

Names that are likely to be confused must be avoided. The   use of meaningful names also aids in understanding and maintenance of programs.

    Descriptive comments should be embedded within the body of source code to describe processing steps.

Statement  Construction:

          Although the flow of  logic is decided during design, the construction Uof individual statements  is done  at the  coding stage. Each statement should be simple & direct. While multiple statements per line allowed, try to use only one statements per line with necessary   indentation. Consider  the following code:

                             If(quantity>0)  { code  =  0; quantity

                             = rate; } else { code = 1; sales = 0 }

Although it is perfectly valid, it could be reorganized as follows:

                             If(quantity>0)

                             {

                                      Code = 0;

                                      Quantity = rate;

                             }

                                    Else

                             {

                                      Code = 1;

                                      Sales = 0;

                             }

The general guidelines for construction of statements are:

1.     Use one statements per line.

2.     Use proper indentation when selection and looping structures are implemented

3.     Avoid heavy nesting of loops,  preferably  not more than three levels.

4.     Use simple conditional tests; if necessary break complicated conditions into simple conditions.

5.     Use parameters to clarify logical and arithmetic expressions.

6.     Use spaces, wherever possible, to improve readability.

Input/Output Formats:

 Input/output formats should be simple and acceptable to user. A number of guidelines should be considered during coding. Keep formats simple.

·        Use ena-of-file indicators, rather than  user requiring  to specify the number of items.

·        Label all interactive input requests.

·        Label all output reports.

·        Use output messages when the output contains some peculiar results.

Generality of Programs:

          Care should be taken to minimize the dependence of a program on a particular set of data, or on a particular value of a parameter. Example:

                                      For(sum = 0, i =1; i  <= 10; i++)

                                                Sum = sum + i;

This loops adds numbers 1, 2, ….. 10. This can be made for general as follows:

                             sum = 0;

                             for(i = m; i <= n; i = i + step);

                                   sum = sum + i;

The initial value m, the final value n, and increment size step can be specified  interactively durin program execution. When m =2, n =100, and step = 2, then loop adds all even numbers upto, and including 100.  

Programming Tutorial

No comments on “Programming Tutorial”

 

First starting with c++


prerequisite for this is c some guys get books of deep c i hope

This tutor designed for noobs so anybody who knows c++ well just keep quiet and dont show off ur ...... etccc

i go slowly one chapter per day starting some theories it may quite boring pls adopt that

if u wont understand some concepts later we go by examples u can understand everything .....


after the session overs any doubts just leave ur questions here...

about compiler its ur wish ....

i wont help the compiler configuration and all ..... download it via software zones...

That's it

lets start c++

A little history

The C++ programming language was initially created by Bjarne Stroustrup, as a "better C". C++ was an attempt to extend and (to some extent) change the C programming language to overcome some problems. C++ standardized in 1998.

Should I Learn C First?

The question arises in ur mind .For my tutorial u should have learnt atleast upto for loop,functions. Because C++ is a superset of C. I have one good book for c named deep c …leave mail id in my scrap I will send through mail mention everything properly.

Comparison c++ with other languages

After learnin this tutorial …. Finally I will tell.

skipping

variables, conditional statements, loops ,operators, functions. These r similar in C.

 

What Is a Program?



The word program is used in two ways: to describe individual instructions, or source code,created by the programmer ex. Hello.cpp and to describe an entire piece of executable software.ex.hello.exe

Move to compiler

-----------------Top 6 c-c++ compiler-------------------



1. DevC++
2. MinGW Studio
3. GNU Emacs and XEmacs
4. Microsoft Visual C++ 2005
5. Eclipse for C++ with CDT
6. Code::Blocks

Compiler types


16-bit compiler ex: familiar one turbo c++
32-bit compiler ex: Microsoft Visual C++ 2005
64-bit compiler
Wat makes difference
In 16 bit compiler the int size is 2 bytes
For 32 bit int size is 4 bytes
Check out using sizeof() operator

Now compiling phases


First u will create a code using any editor even our notepad is a editor.
Most of them have turbo c++ but i recommend move to mingw studio or Microsoft
Turbo c++ also u can practice


code:


#include
int main()
{
std::cout << "Hello world!" << std::endl;
return 0;
}


And save it as hello.cpp

-->>Note: wait look the code once .. std ve u heard about it …. Note it that is namespace
>> When u compile ur code converted into hello.obj or hello.o

>>Before compilation, a special program called the preprocessor scans the source code and preforms simple substitution.

>>The preprocessor examines all lines beginning with # , performs the corresponding actions and macro replacements, and produces a preprocessed version of your program with the file name suffix .i. The .i file is created in a directory used to store temporary files.
>>Preprocessor is separate topic will be discussed elaborately later.

>>Compiler ensures that the code is valid(syntax checking like that) and will sequence into an executable program(sequence arrangement for execution). Under some compilers, you may get messages or warnings with your program
alt

Wat this hello.obj or hello.o contains?


The .o or .obj contains the binary version of the source code which is not directly executable.


>>The final form hello.exe
Here we have one component named linker which combines the object codes into one complete program by integrating libraries(header files) and the code(program which contains 2 or more source codes in separate files ) and producing an executable program.

>>>>>Note: reversing using c++ object code to exact source code is almost impossible to do.If u get many tools in net about reversing but 98% will not give the exact source.Maybe if u wanna knw more about reversing ask some forms and do and report here I got no practice in that .. I too will learn

Wat is class and object?


Ex : Apple is a fruit
Class : fruit
Object :apple

(classes)
• Putting behaviors (functions) and attributes (data) together.
• A class does not exist in the memory of computer during program execution.
(Object)
• An instance of a class. There can be more than one instance for a class.


Frm above example
Consider fruit
Lets check out fruits attributes

(programmatic view inside C++ program looks like this…)

Fruit color - string strFruitColor;
Fruit name - string strFruitName;



Lets check out fruits behaviors
Fruit weight
int weight(string strFruitName)
{
// some code to find weight
return intFruitWeight;
}

code:

class Fruit {
// fields
string strFruitColor;
string strFruitName;

// a function
int weight(string strFruitName)
{
// some code to find weight
return intFruitWeight;
}
}

move to encapsulation, polymorphism,inheritance

What is encapsulation? What’s its uses?


In general the definition is hiding the non-essential characteristics to others.
ex:
->If I want to show the gifts I have received from my girlfriend I'll show otherwise I'll hide them If I don’t wish to.
-> in simple means just hiding the some data in one class not sharing to other class … ex will be given when we move to access specifier topic.

()()Uses:()()
Just hiding our data by covering up (encapsulating) from others…

What is polymorphism?


->It means multiple possible states for a single property.
->polymorphism (Poly-many, orphism-form).
->Consider u ve one elder brother he is lecturer of ur class
U will act bro in ur home and student to ur bro in college… u r taking some forms (now its clear)
->The concept of polymorphism applies to both data types and functions.

()()Purpose:()()
Need to override or overload to change the function behaviors according to the application.

what is Inheritance?


even child knows inheritance
->Acquiring some of the common qualities from parents (for instance eyes like mother, a mole like father etc..) is called inheritance.
->In oop it can also be defined as acquiring some property from others is called inheritance. Based on the sources it differs.

()()Uses:()()
->Inheritance is intended to help reuse existing code with little or no modification.
->The new classes, known as derived classes, inherit attributes and behavior of the pre-existing classes, which are referred to as base classes.
all install compilers and learn c

the best book for c is deep c by ganesan have it

i will continue tomorrow
cheers !!!

Some Library functions in C Part 2

No comments on “Some Library functions in C Part 2”

String Manipulation function

strcat          appands one string to another

strchr          finds first occurence of a given character in string

strcmp       compares two strings

strcmpi      compares two strings without regard to case

strcpy         copies one string to another

strdup         duplicates a string

stricmp       compares two strings without regard to case

strlen           Finds length of a string

strlwr           coverts a string to lower case

strncat         Appends a portion of one string to another

strncmp      Compares a portion of one string with portion of another string

strncpy        copies a given number of characters of one string to another

strnicmp     compares a potion of one string with a portion of another without regard to case

strrchr         finds last occurence of a given character of a string

strrev           reverses a string

strset          sets all characters in a string to a given number

strstr           Finds first occurence of a given string in another string

strupr          converts a string to upper case

 

I/O Funcions

 

Close            closes a file

fclose            Closes a file

feof                detects end-of-file

fgetc              reads a character from a file

fgetchar        reads a character from keyboard

fgets             reads a string from a file

fopen           Opens a file

fprintf            Writes a formated display to a file

fputc             writes a character to a file

fputchar       writes a character to screen

fputs             writes a string to a file

fscanf           reads formatted data from a file

fseek            repositions file pointers to a given location

ftell                gets current file pointer position

getc               reads a character from a file

getch            reads  a chracter from a keyboard

getche          reads a character from keyboard and echoes it

getchar         reads a charcter from keyboard

gets               reads a line from keyboard

inport            reads a two-byte word from a specified port

inportb          reads one byte from the specified I/O port

kbhit              checks for a keystroke at a keyboard

lseek             repositions file pointers to a given location

open             opens a file

outport          writes a two-byte to the specific I/O port

outportb        writes one-byte word to the specific I/O port

printf              Writes formatted data to the screen

putc               Writes a character the file

putch           writes a character to the screen

putchar         writes a character to screen

puts              writes a line to file

read              reads data from file

rewind           repositions file pointer to beginning of a file

scanf             reads formatted data from keyboard

sscanf          reads formatted input froma string

sprintf            writes formatted output to  a string

tell                  gets current file pointer position

write               writes data to a file

 

Directory control functions

 

chdir                    changes current working directory

getcwd                 gets current working directory

fnsplit                    splits a full path name into its components

findfirst                 searches a sisk directory

findnext                  continues findfirst search

mkdir                     makes a new directory

rmdir                      removes a directory

Some Library functions in C

No comments on “Some Library functions in C”

Arithmetic functions

abs   returns absolute value of the integer

cos   calculates cosine

cosh  calculates hyperbolic cosine

exp     raises the exponential e to the xth power

fabs    finds absolute value

floor    find largest integer less than or equal to argument

fmod   finds folating point reminder

hypot   calculates hypotunese of right triangle

log       calculates natural algorithm.

log10  calculates base 10 algoritm

modf    breaks down argument into integer and fractional parts

pow       calculates a value raised to power

sin        calculates sine

sinh      calculates hyperbolic sine

sqrt        finds square root

tan         calculates tangent

tanh       calculates hyperbolic tangents

 

Character classification functions

isalnum      tests for alphanumeric character

isalpha       tests for alphabetic character

isdigit          tests for decimal digit

islower        tests for lowercase characters

isspace       tests for white space character

isupper        tests for uppercase character

isxdigit          tests for hexadecimal digits

tolower         tests characters and converts to lower if its in uppercase

toupper        tests a characters and coverts to upper if its in lowercase

 

Data conversion functions

atof              converts string to float

atoi              converts string to int

atol              converts string to long

ecvt              converts double to string

fcvt               converts double to string

gcvt              converts double to string

itoa              converts int to string

ltoa              converts long to string

strtod          converts string to double

strtol           converts string to long integer

strtoul         converts string to unsigned long integer

ultoa           converts unsigned long to string

 

Searching and sorting functions

bsearch          for binary search

lfind                 for linear search for given value

qsort               for quick sort

 

File handling functions

remove          Delete files

rename         Renames files

unlink            Delete files

 

Disk I/O functions

absread             reads absolute disk sectors

abswrite             writes absolute write sectors

biosdisk            performs bios disk services

getdisk              gets current drive number

setdisk              sets current disk drive

 

Memory allocation functions

calloc           allocates a block of memory

farmalloc     allocates memory from far heap

farfree          frees a block from far heap

free               frees a block allocates with malloc

malloc         allocates a block of memory

realloc         reallocates a block of memory

More Articles …

  1. Function prototype
  2. Function Prototype Example (with Function arguments)
  3. An inline function.
  4. String copy function in c++
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

Page 17 of 21

  • About Us
  • Faqs
  • Contact Us
  • Disclaimer
  • Terms & Conditions