Try-catch not working - why does this throw an Exception?

J

Jon Maz

Hi All,

The following code throws a "CS0020: Division by constant zero Exception".
I would have expected to see a nice, friendly "caught an exception" written
to the screen.

Can anyone explain?

TIA,

JON


<%@ Page Language="C#" %>

<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
try
{
int blob = 1/0;
}
catch(Exception ex)
{
Response.Write("caught an exception");
}
}
</script>
 
J

Jon Maz

Aha... Then the fact that inline .aspx pages only compile when they're first
run makes no difference?

J
 
J

Jon Skeet [C# MVP]

Jon Maz said:
The following code throws a "CS0020: Division by constant zero Exception".
I would have expected to see a nice, friendly "caught an exception" written
to the screen.

Can anyone explain?

Sure - it's an error at compilation time, not at runtime. The catch
block only "counts" at runtime.
 
K

Karl Seguin

This isn't a runtime error (which try/catch work on) but an actual
compilation error...

If you change your code to:
int test = 0;
try {
int blob = 1/test;
} catch {
Response.Write("caught an exception");
}

you'll see the exception caught.

In other words, the Page_Load isn't actually getting executed, simply
compiled...and the compiler is thankfully letting you know there'll always
be an error with your code....always better to have compiler-time errors
than runtime exceptions.

Karl
 
J

Jon Skeet [C# MVP]

Jon Maz said:
Aha... Then the fact that inline .aspx pages only compile when they're first
run makes no difference?

Makes no difference in what way? It certainly doesn't make a difference
to when errors occur. It's not your code that's throwing an exception -
it's the compiler, basically.
 
J

Jon Maz

Yeah, Karl, you're getting a bit slow in your old age...

;-)

Actually your code snippet helped - I am bathed in the light of
understanding...

Thanks!

JON
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,440
Members
44,830
Latest member
ZADIva7383

Latest Threads

Top