Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Not all code paths return a value' using 'try and catch' block

Tags:

c#

try-catch

I have the following interfaces:

//define a method to create a Stream from a generic source
interface IStream
{
    Stream GetStream();
}

and

//define a method to deserialize an object from a stream
interface IDeserializer<T>
{
    T GetObject();
}

and the two following classes that implement them:

//create a new Stream from a URL source
class UrlReader : IStream
{
    private String url;

    public UrlReader(String u)
    { url = u; }

    public Stream GetStream()
    {
        using (var client = new WebClient())
        {
            Stream stream = client.OpenRead(url);
            return stream;
        }
    }
}

and

//deserialize a JSON object implementing the interface IDeserializer
class JsonDeserializer<T> : IDeserializer<T>
{
    private String json;

    public JsonDeserializer(String j)
    { json = j; }

    public T GetObject()
    {
        return JsonConvert.DeserializeObject<T>(json);
    }
}

I would like to add the try and catch block to both methods to manage exceptions however if I do so not all code paths will return a value. I know a way to resolve this problem is to decalre and initialize the variable to return before the try block. However I cannot initialize a variable of type Stream as this is an abstract class and I cannot initialize a variable of generic type T. Can you please advise how to solve this problem?

like image 519
UbuntuDude Avatar asked Mar 19 '26 12:03

UbuntuDude


1 Answers

You either need to find a concrete implementation of a Stream, such as a MemoryStream, create an instance and return it

or

return null in which case someone else may run into a NullReferenceException

or

let the exception go though.

Think about it, whether it is a good idea of returning a stream that is empty. Someone will try to read from it and run into other issues.

An exception is not such a bad idea because it leaves the decision of what to do to the user of the function.

like image 67
Thomas Weller Avatar answered Mar 22 '26 02:03

Thomas Weller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!