Reputation: 524
I try to build a simple application in Visual Studio that involves a Microsoft Access database file, but I noticed that when I am opening the connection to the database I do not get a compile error although I should be warned at least, because that method throws an exception.
Of course I did noticed the exception after it was thrown (piece of code with the comment bellow), during the compiling procedure.
So how am I supposed to figure out when I shall use a try-catch block or how at least I am going to be warned for a method which throws an exception in Visual C#?
namespace DBTest
{
public partial class Form1 : Form
{
String connectionstring = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=Accounts1.mdb";
OleDbConnection conn;
public Form1()
{
InitializeComponent();
conn = new OleDbConnection(connectionstring);
MessageBox.Show(conn!=null?"Connected to Database":"Didnt connected to Database", "Database:");
}
private void button1_Click(object sender, EventArgs e)
{
conn.Open(); //The exception was THROWN HERE!
String myQuery = "select * from mode";
OleDbCommand cmd = new OleDbCommand(myQuery, conn);
OleDbDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MessageBox.Show(reader.GetValue(1).ToString());
}
}
}
}
Upvotes: 1
Views: 103
Reputation: 3871
That’s a runtime exception so the compiler can’t help you with catching it at a compile time. And the try-catch
block helps you to handle this exception, not to prevent it from being thrown at the runtime. If you don’t make a try-catch block it will be handled at a general application level.
A quote from MSDN:
When an exception is thrown, the common language runtime (CLR) looks for the catch statement that handles this exception. If the currently executing method does not contain such a catch block, the CLR looks at the method that called the current method, and so on up the call stack. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program.
Please refer to the MSDN try-catch for more information.
Upvotes: 0
Reputation: 69372
You may be coming from a background of Java with its checked exceptions but not handling an exception is not a compiler error or a warning (albeit can be good practice at times). To see what exceptions are thrown, you can read the documentation of the method or hover your mouse over the method name.
Upvotes: 2