Click here to Skip to main content
15,913,101 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
For example in console i must input 3 datas`
string,string,int
.
if I write any of the words wrongly,for example first data i wrote as integer,it will warn me with any message,for example`
(some data are not correct)

How can i write that Exception through try catch,which condition i must write in try catch?

What I have tried:

Maybe i must write with int.TryParse?
Posted
Updated 7-Feb-18 1:18am
Comments
Leo Chapiro 7-Feb-18 5:55am    
>Maybe i must write with int.TryParse -> Maybe.
What gone wrong with this approach?
Suren97 7-Feb-18 5:58am    
i didn't try,i don't know how write it

As input, a number is a valid string: you won't get an exception.
Write your own validation method for the sequence of input parameters.
Such method could return a bool (like TryParse), an error code (in order to get more information) or even thrown an Exception (that calling code should then handle it).
 
Share this answer
 
You could use exceptions, but exceptions are expensive for the code to generate and shouldn't really be used as validation, especially when there is a likelihood the conversion will fail, such as when validating input from the user.

Instead you should use string.split (google for examples) to split the string on the comma, then go through each segment and use the appropriate TryParse function, so int.TryParse, bool.TryParse etc to validate them in turn. Again just google for examples of how to use int.tryParse etc.
 
Share this answer
 
For int you must try TryParse method.

For string u can typecast like :

int intA = 10;
string a = (string) intA;

but sometimes this may throw exceptions.

Instead try using : 

int intA = 10;
string a = Convert.ToString(intA);

The Convert.ToString() method will never throw exception and handles null as well when compared to typecasting.
 
Share this answer
 
Comments
phil.o 7-Feb-18 7:50am    
string a = intA.Tostring();

Using Convert class to get the string representation of an integer is not really a good practice. As for an integer parameter, there is no null reference exception to handle since int is a valuetype and thus can never be null.
Shashank Laxman 7-Feb-18 8:20am    
The question in itself is a joke

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900