mowwwalker
mowwwalker

Reputation: 17364

Try, Catch inside constructor that calls base constructor

Sorry for the confusing title. Basically I made a BinaryReader class that reads in big endian and set its constructor up as:

BinaryReader2(System.IO.Stream strm) : base(strm){}

I was told that you can't call the base class's constructor any other way, and that this was the best way to do it.

The problem is that when another program has control of a file I'm trying to read, it doesn't display any error messages (because I'm new to programming and didn't set up any try catch statements..). So, I'm trying to account for all the possible situations by using try-catch statements. I've never used them before, so I was hoping I could get a few pointers on it.

I created the binaryreader2 class in many places throughout the program and was hoping I could set up the try catch inside the binaryreader class itself instead of in each of the places I used it. Is it possible to do that and still call the base class's constructor?

Upvotes: 1

Views: 1138

Answers (2)

radarbob
radarbob

Reputation: 5101

I've never used them before, so I was hoping I could get a few pointers on it.

  • In general put Try/Catch around code that "goes outside" for something. Things your program has no control over. Fetching a file, getting stuff from a database, etc.

  • Try-Block as little code as possible. For example wrap just the file fetch call in Try, not all the stuff happening after that. I.E. as @Marc said above, once you have a valid FileStram object there's no point in putting that in the Try block.

  • If you do the above you can then Catch very specific exception types. This will allow you to give good error messages about the problem, or otherwise handle the problem in code so your program does not have to just blow up.

  • Study carefully the difference between re-throwing the original exception vice throwing a new exception instance.

  • Suggestion: Wrap your initial Run() in a Try and in the Catch block do something with it. Learn about "publishing". You can send yourself an email for example. Stuff the exception in a database, write to a log file.

  • With the above then in every Catch everywhere in your application, always re-throw (see my warning above) the exception and you have a single point where you do something useful with it.

Upvotes: 0

Jahan Zinedine
Jahan Zinedine

Reputation: 14874

One possible workaround: Use composition over inheritance. this way you have a better control on initializing the formerly base object.

Upvotes: 1

Related Questions