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

Discussion in 'ASP .Net' started by Jon Maz, Oct 25, 2004.

  1. Jon Maz

    Jon Maz Guest

    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>
     
    Jon Maz, Oct 25, 2004
    #1
    1. Advertisements

  2. Jon Maz

    Jon Maz Guest

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

    J
     
    Jon Maz, Oct 25, 2004
    #2
    1. Advertisements

  3. Sure - it's an error at compilation time, not at runtime. The catch
    block only "counts" at runtime.
     
    Jon Skeet [C# MVP], Oct 25, 2004
    #3
  4. Jon Maz

    Karl Seguin Guest

    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
     
    Karl Seguin, Oct 25, 2004
    #4
  5. Jon Maz

    Karl Seguin Guest

    wow, I was late to the party on this one...

    karl
     
    Karl Seguin, Oct 25, 2004
    #5
  6. 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.
     
    Jon Skeet [C# MVP], Oct 25, 2004
    #6
  7. Jon Maz

    Jon Maz Guest

    Thanks for the help!

    JON
     
    Jon Maz, Oct 25, 2004
    #7
  8. Jon Maz

    Jon Maz Guest

    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
     
    Jon Maz, Oct 25, 2004
    #8
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.