Exception Handling
Exception Handling
vb 1
1 'ques 1
2 'Module Module1
3 ' Public Class NegativeMarkException
4 ' Inherits ApplicationException
5 ' Public Sub New(message As String)
6 ' MyBase.New(message)
7 ' End Sub
8 ' End Class
9
10 ' Sub Main()
11 ' Try
12 ' Dim totalMarks As Integer = 0
13 ' Dim marks(4) As Integer
14
15 ' For i As Integer = 0 To 4
16 ' Console.WriteLine("Enter marks for subject " & (i + 1) &
":")
17 ' Dim input As String = Console.ReadLine()
18
19 ' If Not Integer.TryParse(input, marks(i)) Then
20 ' Throw New Exception("Non-numeric value entered.")
21 ' End If
22
23 ' If marks(i) < 0 Then
24 ' Throw New NegativeMarkException("Negative marks are
not allowed.")
25 ' End If
26
27 ' totalMarks += marks(i)
28 ' Next
29
30 ' Dim percentage As Double = (totalMarks / 500) * 100
31 ' Console.WriteLine("The student's percentage is: " & percentage
& "%")
32
33 ' Catch ex As NegativeMarkException
34 ' Console.WriteLine(ex.Message)
35 ' Catch ex As Exception
36 ' Console.WriteLine("Error: " & ex.Message)
37 ' End Try
38 ' End Sub
39
40 'End Module
41
42 'ques 2
43
44 'Module Module1
45 ' Public Class InvalidNameException
46 ' Inherits ApplicationException
... study\ExceptionHandling\ExceptionHandling\Module1.vb 2
47
48 ' Private errorMessage As String
49
50 ' Public Sub New(message As String)
51 ' errorMessage = message
52 ' End Sub
53
54 ' Public Overrides ReadOnly Property Message As String
55 ' Get
56 ' Return errorMessage
57 ' End Get
58 ' End Property
59 ' End Class
60 ' Function IsAllAlphabets(name As String) As Boolean
61 ' For Each ch As Char In name
62 ' If Not ((ch >= "A"c AndAlso ch <= "Z"c) Or (ch >= "a"c AndAlso
ch <= "z"c)) Then
63 ' Return False
64 ' End If
65 ' Next
66 ' Return True
67 ' End Function
68
69 ' Sub Main()
70 ' Try
71 ' Console.WriteLine("Enter the number of students:")
72 ' Dim studentCount As Integer = Convert.ToInt32(Console.ReadLine
())
73 ' Dim students(studentCount - 1) As String
74
75 ' For i As Integer = 0 To studentCount - 1
76 ' Console.WriteLine("Enter the name of student " & (i + 1) &
":")
77 ' Dim studentName As String = Console.ReadLine()
78
79 ' If Not IsAllAlphabets(studentName) Then
80 ' Throw New InvalidNameException("Invalid name. Only
alphabets are allowed.")
81 ' End If
82
83 ' students(i) = studentName
84 ' Next
85
86 ' Console.WriteLine("Student names have been successfully
collected.")
87
88 ' Catch ex As InvalidNameException
89 ' Console.WriteLine(ex.Message)
90 ' Catch ex As Exception
... study\ExceptionHandling\ExceptionHandling\Module1.vb 3
91 ' Console.WriteLine("Error: " & ex.Message)
92 ' End Try
93 ' End Sub
94
95 'End Module
96