Results 1 to 24 of 24

Thread: finally block: is possible to know if an exception happened

  1. #1

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    finally block: is possible to know if an exception happened

    Dear friends,

    I want to discover if an exception happened, but I want to do this inside the finally block.
    I could create a boolean variable in the try block and set the value to true on catch block if an exception happened, but I'll have to update all methods to this situation, otherwise, If is possible to detect on finally block the impact is lower.

    Here is an example:

    Code:
        Private Sub Test()
            Try
                'normal code implementation
            Catch ex As Exception
                'Exception Handling
            Finally
                'If happened an exception
                Trace(True)
                'If NOT happened an exception
                Trace(False)
            End Try
        End Sub
    
        Private Sub Trace(ByVal err As Boolean)
            'normal code implementation
        End Sub
    Thanks and sorry for my bad English.

  2. #2
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: finally block: is possible to know if an exception happened

    I'd use functions for your situation. The function can return a boolean or some customized object containing information about the exception. You then just call the function and retrieve the returned value, examine it and perform appropriate actions from there.
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  3. #3

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    Ok, but I'll have to call this function in the try and catch blocks? I want to call only in the finally block.

  4. #4
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: finally block: is possible to know if an exception happened

    Finally block is always executed regardless of the outcome of the Try block. It is meant to be used for cleanups. You can do it the way you had in post#1, but it just looks weird to me. If you turn the sub into a function like this,
    Code:
    Private Function Test() As Boolean
            Try
                'normal code implementation
            Catch ex As Exception
                Return False
            End Try
            Return True
        End Sub
    Then you just have to call Trace subroutine like this:
    Code:
    Trace(Test())
    Let us have faith that right makes might, and in that faith, let us, to the end, dare to do our duty as we understand it.
    - Abraham Lincoln -

  5. #5

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    OK, I agree with you, but I would like to get the object Exception.
    What the best implementation to the situation down?

    Example:

    Code:
        Private Function Test() As Integer
            Try
                int i = 0;
                'normal code implementation
                'normal code implementation
                return i;
            Catch ex As Exception
                'normal exception Handling
            Finally
                Trace("IT'S a TESTE", true or false ???, how I get the exception ???)
            End Try
        End Sub
    
        Private Sub Trace(ByVal pAnytext, ByVal err As Boolean, Optional ByVal pException As Exception = nothing)
            If ( err = true ) Then
                 'Use pException to get its properties
            End If
        End Sub

  6. #6
    Addicted Member
    Join Date
    Mar 2008
    Posts
    143

    Re: finally block: is possible to know if an exception happened

    Why not...

    Code:
     
    Private Function Test() As Integer
    	Dim ex As Exception = Nothing
    
    	Try
    		'normal code implementation
    		'normal code implementation
    	Catch ex
    		'normal exception Handling
    	Finally
    		If Not ex Is Nothing Then
    
    			Debug.Print(ex.Message)
    		End If
    	End Try
    End Function
    Shut up and eat your banana!

  7. #7
    A SQL Server fool GaryMazzone's Avatar
    Join Date
    Aug 2005
    Location
    Dover,NH
    Posts
    7,493

    Re: finally block: is possible to know if an exception happened

    I have a globlal var call errMess that is a structure of ErrNumber and the ErrorMessage. At the start of the procedure I set the errMess.ErrNum = 0 and errMess.ErrMessage = string.empty.

    If there is an error the Catch portion will save the ErrorNumber and ErrorMessage to my structure then I can look at the value in errMess.ErrNum if it is not 0 then I display the error message for the user or write it to a log file to send for support.
    Sometimes the Programmer
    Sometimes the DBA

    Mazz1

  8. #8

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    GaryMazzone,

    Okay, so this is correct? (using C#)

    Code:
    public partial class Form1 : Form
        {
    
            private Exception _ex;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                DoTest();
            }
    
            private int DoTest()
            {
                try
                {
                    int i = -1;      //this is only for test
                    int j = 0;       //this is only for test
                    return i / j;    //this is only for test
                }
                catch (Exception ex)
                {
                    _ex = ex;
                    return 0;
                }
                finally
                {
                    MessageBox.Show("finally Erro: " + _ex.Message);
                }
            }
    
        }

  9. #9
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: finally block: is possible to know if an exception happened

    Code:
            Dim i As Integer = 0 'test data
            Dim ii As Integer = 1, iii As Integer 'test data
            '
            Dim Flag As Boolean
            Dim ex As Exception
            Try
                Flag = False 'indicate no exception
                iii = ii \ i
            Catch ex
                Flag = True 'indicate exception
            Finally
                Trace(Flag, ex)
            End Try
        End Sub
    
        Private Function Trace(ByVal err As Boolean, Optional ByVal ex As Exception = Nothing) As Boolean
            If ex Is Nothing Then
    
            Else
                Debug.WriteLine(ex.Message)
            End If
        End Function
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  10. #10

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    dbasnett,

    Thanks, but It works to vb.net but not works on C#:

    Error 1 The type or namespace name 'ex' could not be found (are you missing a using directive or an assembly reference?) F:\Projetos\Rogerio\C#\ExceptionTeste\Form1.cs 33 20 ExceptionTeste


    Code:
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                Test();
            }
    
            private int Test()
            {
                try
                {
                    int i = -1;
                    int j = 0;
                    return i / j;
                }
                catch (ex)
                {
                     return 0;
                }
                finally
                {
                    MessageBox.Show("finally Erro: " + ex.Message);
                }
            }
    Last edited by roglopes; Oct 6th, 2008 at 02:37 PM.

  11. #11
    Fanatic Member
    Join Date
    Feb 2006
    Posts
    607

    Re: finally block: is possible to know if an exception happened

    What are you really getting at here? You have 2 or 3 solutions you can pick from, whats wrong with them.

    Personally I really like the idea of creating a small structure to hold the errornumber + message. Most of the time though I will just use a function if I dont need to know what the error message is and just return true and false.

    if you need the error message then use a structure. If you dont, use the boolean logic.

  12. #12

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    The solution shown by dbasnett is satisfactory, but it only works with vb.net, not on C#.

  13. #13
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: finally block: is possible to know if an exception happened

    Quote Originally Posted by roglopes
    The solution shown by dbasnett is satisfactory, but it only works with vb.net, not on C#.
    Of course his solution is in vb.net... you're asking your question in the vb.net section. So (using common sense, something you're probably not too fond of) if you need a solution to be in c#, shouldn't you have posted in the c# section to start with?
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

  14. #14
    Fanatic Member
    Join Date
    Feb 2006
    Posts
    607

    Re: finally block: is possible to know if an exception happened

    Whats wrong with the code you had where you decalred a global variable of type Exception

  15. #15
    Fanatic Member
    Join Date
    Feb 2006
    Posts
    607

    Re: finally block: is possible to know if an exception happened

    Your way works fine after testing:

    Csharp Code:
    1. static void Main(string[] args)
    2.         {
    3.             Exception _ex;
    4.             _ex = null;
    5.  
    6.             try
    7.             {
    8.                 throw new Exception("test exception");
    9.             }
    10.             catch (Exception ex)
    11.             {
    12.                 _ex = ex;
    13.             }
    14.             finally
    15.             {
    16.                 Console.WriteLine("Finally happened");
    17.                 Console.WriteLine(_ex.Message);
    18.             }
    19.             Console.Read();
    20.         }

  16. #16
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: finally block: is possible to know if an exception happened

    to answer the question asked by the OP, in your C# code, you didn't declare a type of exception to catch.

    Code:
    try
    {
    
    }
    catch (Exception ex)
    {
    
    }
    finally
    {
    
    }

  17. #17
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: finally block: is possible to know if an exception happened

    as a side note, a finally block should never know or care if an exception was caught in a catch block. it is the job of the finally to do clean up and NOTHING else.

  18. #18

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    Quote Originally Posted by masfenix
    Your way works fine after testing:

    Csharp Code:
    1. static void Main(string[] args)
    2.         {
    3.             Exception _ex;
    4.             _ex = null;
    5.  
    6.             try
    7.             {
    8.                 throw new Exception("test exception");
    9.             }
    10.             catch (Exception ex)
    11.             {
    12.                 _ex = ex;
    13.             }
    14.             finally
    15.             {
    16.                 Console.WriteLine("Finally happened");
    17.                 Console.WriteLine(_ex.Message);
    18.             }
    19.             Console.Read();
    20.         }
    Yes, I had already tested and worked, but I wanted to know if it would have a way to not declare the exception in the catch block.

    To all thanks very much for your support.

  19. #19
    I'm about to be a PowerPoster! kleinma's Avatar
    Join Date
    Nov 2001
    Location
    NJ - USA (Near NYC)
    Posts
    23,373

    Re: finally block: is possible to know if an exception happened

    Exception is the base type that all other specific exception types inherit from, so if you catch exception, it is basically a global exception handler in terms of the type of exception it will catch when one occurs in the try. Any type of exception thrown will be caught by 'catch (Exception ex)'

  20. #20
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: finally block: is possible to know if an exception happened

    sorry i thought this was a vb forum.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  21. #21
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: finally block: is possible to know if an exception happened

    dup'ed by accident
    Last edited by dbasnett; Oct 6th, 2008 at 04:40 PM.
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

  22. #22
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: finally block: is possible to know if an exception happened

    To answer the original question: No, you can't do that.

    All the solutions that have been posted here have required that something happen in the Catch block. There's a reason for that and Kleinma pointed out what it was. You are trying to make the Finally block act as a pseudo catch block. However, if the Catch block has dones it's job, then there will be no exception by the time the Finally block has been reached. Therefore, you will have to send a signal to the Finally block that the Catch block has been entered, and the only way to do that is to add code to the Catch block, like it or not.
    My usual boring signature: Nothing

  23. #23

    Thread Starter
    Lively Member roglopes's Avatar
    Join Date
    Sep 2002
    Location
    Brazil
    Posts
    113

    Re: finally block: is possible to know if an exception happened

    Guys, thanks for the explanations.

  24. #24
    PowerPoster JuggaloBrotha's Avatar
    Join Date
    Sep 2005
    Location
    Lansing, MI; USA
    Posts
    4,286

    Re: finally block: is possible to know if an exception happened

    Quote Originally Posted by dbasnett
    sorry i thought this was a vb forum.
    Same here, I guess C# code is best placed in the VB.Net forum, goes to show that C# people need VB's help
    Currently using VS 2015 Enterprise on Win10 Enterprise x64.

    CodeBank: All ThreadsColors ComboBoxFading & Gradient FormMoveItemListBox/MoveItemListViewMultilineListBoxMenuButtonToolStripCheckBoxStart with Windows

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width