virtual
vor die Funktionsdeklaration in der Basisklassevirtual int foo() = 0;
#include <iostream>
using namespace std;
int division(int a, int b) {
if (b == 0) {
throw "Division durch Null";
}
return a/b;
}
int main() {
try {
cout << "10/3=" << division(10,3) << endl;
cout << "12/0=" << division(12,0) << endl;
cout << "14/5=" << division(14,5) << endl;
}
catch (char const* message) {
cout << message << endl; // Lieber cerr nehmen!
}
cout << "Divisionen ausgeführt." << endl;
return 0;
}
#include <iostream>
using namespace std;
class MathError {};
class Overflow: public MathError {};
class SpecialOverflow: public Overflow {};
void schwierigeRechnung(){
throw SpecialOverflow();
}
int main() {
try {
schwierigeRechnung();
}
catch (Overflow) {
cout << "Gefangen: Overflow" << endl;
}
catch (SpecialOverflow) {
cout << "Gefangen: SpecialOverflow" << endl;
}
catch (MathError) {
cout << "Gefangen: MathError" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
class MathError {};
class Overflow: public MathError {};
class SpecialOverflow: public Overflow {};
void schwierigeRechnung(){
throw SpecialOverflow();
}
int main() {
try {
schwierigeRechnung();
}
catch (SpecialOverflow) {
cout << "Gefangen: SpecialOverflow" << endl;
}
catch (Overflow) {
cout << "Gefangen: Overflow" << endl;
}
catch (MathError) {
cout << "Gefangen: MathError" << endl;
}
catch (...) {
// fängt alles andere
cout << "Ausnahme \"...\" gefangen" << endl;
}
return 0;
}
#include <iostream>
using namespace std;
class MeineException {
protected:
string info;
public:
MeineException(const char *n) : info(n) {}
virtual void print() { cout << "info?: " << info << endl; }
};
class DeineException : public MeineException {
public:
DeineException(const char *n) : MeineException(n) {}
void print() { cout << "info!: " << info << endl; }
};
int main() {
try {
throw DeineException("Psst! Geheim!");
} catch (MeineException e) {
e.print();
}
try {
throw DeineException("Psst! Geheim!");
} catch (MeineException &e) {
e.print();
}
return 0;
}
#include <iostream>
using namespace std;
struct Member{
Member() { cout << "Member Konstruktor" << endl; }
~Member() { cout << "Member Destruktor" << endl; }
};
struct MyClass{
Member member;
MyClass() {
cout << "MyClass Konstruktor" << endl;
throw 23;
}
~MyClass() { cout << "MyClass Destruktor" << endl; }
};
int main() {
try {
MyClass mc{};
} catch (int i) {
cout << "Caught Exception " << i << endl;
}
return 0;
}
throw std::exception()
try { } catch (std::exception e) {}
#include <iostream>
using namespace std;
class Error {
public:
string info;
Error(string _info) : info(_info) {}
};
void mehrArbeit(int a) {
if (a == 0) {
throw Error(":-(");
}
}
void arbeit() {
try {
mehrArbeit(0);
} catch(Error e) {
throw "FEHLER!!!";
}
}
int main() {
try {
arbeit();
} catch (Error e) {
cout << "Error: " << e.info << endl;
} catch (...) {
cout << "Unknown exception caught" << endl;
}
return 0;
}