How to know the Exception name to use in code?

kak.mca

New member
Joined
Jan 28, 2008
Messages
3
Programming Experience
Beginner
Hi,
Good morning to All.

This post might look like silly, but I couldn't get clear idea on this. I need some help to proceed further. Please help me on this.

I can express my doubt with one example.

PHP:
Public Class ThrowDemo

    Private Sub ThrowDemo_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim x As Single = getAverage(0, 100)
        MessageBox.Show(x)
    End Sub

    Private Function getAverage(ByVal items As Integer, ByVal total As Integer) As Single
        Try
            Dim sngAverage As Single = CSng(total / items)
            Return sngAverage
        Catch ex As DivideByZeroException
            MessageBox.Show("Calculation generated DivideByZero Exception")
        End Try
    End Function
End Class

Now, my doubt is:

How can one novice developer know the exception name DivideByZeroException to put in the code. If he is intellegent, then he can predict in advance that chances are there for division by zero error to occur. But how can he know that DivideByZeroException is the exception name to handle such type of situation?

In other words:

How can I get those exception names(like, for example: DivideByZeroException) to put in exception block for exceptions that might occur.

Thanks in Advance,
Ashok kumar.
 
How can you get any class names? Look them up in the MSDN Library. The documentation for the Exception class provides a link to all the classes derived from that class. One of those classes is System.SystemException, and if you follow the link to that topic you're provided with a link to all the classes derived from that. Etc., etc.

That said, an intelligent developer would not have to catch a DiveideByZeroException there because they would test the value of the 'items' variable first to make sure it wasn't zero. You should never catch exceptions that could be simply prevented by validation.

Also, most of the exceptions that you do need to catch will be thrown by methods that you call and the documentation for those methods will generally tell you what exceptions they can throw. Also, if you don't implement exception handling and an exception is thrown the IDE will tell you exactly what type of exception was thrown.
 
Back
Top