Você está na página 1de 11

EXCEPTIONS

Exceptions provide a way to react to exceptional


circumstances (like runtime errors) in programs by
transferring control to special functions
called handlers.
EXAMPLE
// exceptions
#include <iostream.h>
int main ()
{
try
{
throw 20;
}
catch (int e)
{
cout << "An exception occurred. Exception Nr. "
<< e << '\n';
}
return 0;
}
EXCEPTIONS
A throw expression accepts one parameter (in this
case the integer value 20), which is passed as an
argument to the exception handler.
MULTIPLE HANDLER
Multiple handlers (i.e., catch expressions) can be
chained; each one with a different parameter type.
Only the handler whose argument type matches the
type of the exception specified in
the throw statement is executed.
try
{ // code here }
catch (int param)
{ cout << "int exception"; }
catch (char param)
{ cout << "char exception"; }
catch (...)
{ cout << "default exception";
}
EXCEPTIONS
After an exception has been handled the program,
execution resumes after the try-catch block, not
after the throw statement!.
C++ provides the following classes to perform
output and input of characters to/from files:

ofstream: Stream class to write on files
ifstream: Stream class to read from files
fstream: Stream class to both read and write
from/to files

INPUT/OUTPUT WITH FILES

BASIC FILE OPERATIONS
// basic file operations
#include <iostream.h>
#include <fstream.h>
int main ()
{
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n"; myfile.close();
return 0;
}
OUTPUT TO TEXT FILE
// writing on a text file
#include <iostream>
#include <fstream>
int main ()
{
ofstream myfile ("example.txt");
if (myfile.is_open())
{ myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close(); }
else cout << "Unable to open file";
return 0;
}
READING FROM FILE
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
int main ()
{
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{ while ( getline (myfile,line) )
{ cout << line << '\n'; }
myfile.close(); }
else cout << "Unable to open file"; return 0; }

Você também pode gostar