MS Exam 70-536 - How to throw and handle exception from thread?
Posted
by Max Gontar
on Stack Overflow
See other posts from Stack Overflow
or by Max Gontar
Published on 2010-03-17T16:09:47Z
Indexed on
2010/03/17
16:11 UTC
Read the original article
Hit count: 221
Hello! In MS Exam 70-536 .Net Foundation, Chapter 7 "Threading" in Lesson 1 Creating Threads there is a text:
Be aware that because the WorkWithParameter method takes an object, Thread.Start could be called with any object instead of the string it expects. Being careful in choosing your starting method for a thread to deal with unknown types is crucial to good threading code. Instead of blindly casting the method parameter into our string, it is a better practice to test the type of the object, as shown in the following example:
' VB
Dim info As String = o as String
If info Is Nothing Then
Throw InvalidProgramException("Parameter for thread must be a string")
End If
// C#
string info = o as string;
if (info == null)
{
throw InvalidProgramException("Parameter for thread must be a string");
}
So, I've tried this but exception is not handled properly (no console exception entry, program is terminated), what is wrong with my code (below)?
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(SomeWork);
try
{
thread.Start(null);
thread.Join();
}
catch (InvalidProgramException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
Console.ReadKey();
}
}
private static void SomeWork(Object o)
{
String value = (String)o;
if (value == null)
{
throw new InvalidProgramException("Parameter for "+
"thread must be a string");
}
}
}
Thanks for your time!
© Stack Overflow or respective owner