try (C++)
Nach oben zu Schlüsselwörter alphabetisch - Index
Kategorie
Anweisungen, C++-spezifische Schlüsselwörter
Syntax
try compound-statement handler-list
Beschreibung
Das Schlüsselwort try wird nur in C++-Programmen unterstützt. In C-Programmen sollten Sie __try verwenden. In C++ ist auch __try zulässig.
Einem Programmblock, in dem eine Exception auftreten kann, muss das Schlüsselwort try vorangestellt werden. Nach "try" folgt ein in geschweifte Klammern eingeschlossener Codeblock. Damit wird festgelegt, dass das Programm in diesem Teil prüft, ob Exceptions auftreten. Tritt eine Exception auf, wird der Programmablauf unterbrochen. Folgende Schritte werden dann ausgeführt:
- Das Programm sucht nach einer passenden Behandlungsroutine.
- Wird eine Behandlungsroutine gefunden, wird der Stack bis zu diesem Punkt "zurückgespult".
- Die Programmsteuerung geht auf die Behandlungsroutine über.
Wenn keine Behandlungsroutine gefunden wird, ruft das Programm die Funktion "terminate" auf. Wenn keine Exceptions auftreten, läuft das Programm in der normalen Weise ab.
Beispiel
Das folgende Codefragment zeigt die Verwendung des try/__finally-Konstrukts:
#include <stdio.h>
#include <string.h>
#include <windows.h>
class Exception
{
public:
Exception(char* s = "Unknown"){what = strdup(s); }
Exception(const Exception& e ){what = strdup(e.what); }
~Exception() {free(what); }
char* msg() const {return what; }
private:
char* what;
};
int main()
{
float e, f, g;
try
{
try
{
f = 1.0;
g = 0.0;
try
{
puts("Another exception:");
e = f / g;
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
puts("Caught a C-based exception.");
throw(Exception("Hardware error: Divide by 0"));
}
}
catch(const Exception& e)
{
printf("Caught C++ Exception: %s :\n", e.msg());
}
}
__finally
{
puts("C++ allows __finally too!");
}
return e;
}
Das obige Programm erzeugt die folgende Ausgabe:
Another exception: Caught a C-based exception. Caught C++ exception[Hardware error: Divide by 0] C++ allows __finally too!