How to handle invalid argument in VB.NET

3 Answers

0 votes
Imports System
 
Class Program
    Public Shared Sub SetAge(ByVal age As Integer)
        If age < 0 OrElse age > 120 Then
            Throw New ArgumentException("Age must be between 0 and 120.")
        End If
 
        Console.WriteLine($"Age set to {age}")
    End Sub
 
    Public Shared Sub Main()
        SetAge(121)
    End Sub
End Class
 
 
 
' run:
'
' Unhandled exception. System.ArgumentException: Age must be between 0 and 120.
'   at Program.SetAge(Int32 age)
'   at Program.Main()
'

 



answered May 20, 2025 by avibootz
edited May 20, 2025 by avibootz
0 votes
Imports System

Class Program
    Public Shared Sub SetName(ByVal name As String)
        If String.IsNullOrWhiteSpace(name) Then
            Throw New ArgumentNullException(NameOf(name), "Name cannot be null or empty.")
        End If

        Console.WriteLine($"Name set to {name}")
    End Sub

	Public Shared Sub Main()
        SetName("")
    End Sub
End Class



' run:
'
' Unhandled exception. System.ArgumentNullException: Name cannot be null or empty. (Parameter 'name')
'   at Program.SetName(String name)
'   at Program.Main()
'

 



answered May 20, 2025 by avibootz
0 votes
Imports System

Class Program
    Public Shared Sub ProcessInput(ByVal input As String)
        Try
            If String.IsNullOrEmpty(input) Then
                Throw New ArgumentException("Input cannot be null or empty.")
            End If

            Console.WriteLine($"Processing input: {input}")
        Catch ex As ArgumentException
            Console.WriteLine($"Error: {ex.Message}")
        End Try
    End Sub

    Public Shared Sub Main()
        ProcessInput("")
    End Sub
End Class
 
 
 
' run:
'
' Error: Input cannot be null or empty.
'

 



answered May 20, 2025 by avibootz

Related questions

4 answers 334 views
4 answers 354 views
4 answers 312 views
4 answers 294 views
3 answers 246 views
3 answers 248 views
...