Problem mit Try/Catch-Block
-
Mein Compiler scheint Anweisungen, die innerhalb eines Try-Blocks stehen, zu ignorieren
try {
int x, wert;
cin >> x;
IntFeld f(x);
}
catch(string s) {
cout << "Fehler: " << s << endl;
}Der Compiler beschwert sich dann, dass er x und wert als Variable nicht kennt.
Ich verwende Visual c++ 2008 Express Edition.
-
Zeige mal den vollständigen Code, mit main() und includes etc.
-
theta schrieb:
Zeige mal den vollständigen Code, mit main() und includes etc.
/////////////// IntFeld.h ///////////////////////////// #pragma once #include <iostream> #include <string> class IntFeld { int *feld; int groesse; public: IntFeld(int g); ~IntFeld() { delete[](feld); } void setWert(int pos, int wert) { feld[pos]=wert; } int getWert(int pos) const { return(feld[pos]); } }; ////////////// IntFeld.cpp //////////////////////////////////////// #include "stdafx.h" #include "IntFeld.h" #include <iostream> using namespace std; IntFeld::IntFeld(int g): groesse(g) { if(g<0) throw string("Negative Feldgroesse!"); feld = new int[groesse]; } /////// main.cpp ////////////////////////// #include "stdafx.h" #include "IntFeld.h" #include <iostream> using namespace std; void main() { cout << "Wie viele Werte:"; try { int x, wert; cin >> x; IntFeld f(x); } catch(string s) { cout << "Fehler: " << s << endl; } for (int i=0; i<x; ++i) { cout << "Wert " << i+1 << ":"; cin >> wert; f.setWert(i,wert ); } for (int i=0; i<x; ++i) cout << f.getWert(i) << " " << endl; }
Der Compiler beschwert sich nun, dass er x und wert nicht kennt.
-
try { int x, wert; cin >> x; IntFeld f(x); } catch(string s) { cout << "Fehler: " << s << endl; } //x und wert SIND HIER NICHT BEKANNT! for (int i=0; i<x; ++i) { cout << "Wert " << i+1 << ":"; cin >> wert; f.setWert(i,wert ); }
Du muss x und wert außerhalb des try-Blocks deklarieren!
Bsp:{ int x; x = 1; } x = 10; //FEHLER: x unbekannt;
int x; { x = 1; } x = 10; //OK
-
Danke, das war die Lösung. War in meinem Lehrbuch nicht beschrieben.