Is this the best way for me to abort instantiation of an object if it's parameters are not passed in with valid data?
protected Command(string commandKey)
{
if(commandKey == null) throw new ArgumentNullException("commandKey", "Command Key cannot be null as it is required internally by Command");
if(commandKey == "") throw new ArgumentException("Command Key cannot be an empty string");
CommandKey = commandKey;
}
Yes. It is common practice to validate the arguments in constructors and throw an exception if they are invalid.
It's perfectly fine. Constructors do not return anything so how else would you know if something went wrong? You could have a bool to set it to some uninitialized state but I would go with exceptions.
Also :
if(String.IsNullOrEmpty(commandKey)) //throw exectpion
In this case you could use the static method string.IsNullOrEmpty(commandKey):
protected Command(string commandKey)
{
if(string.IsNullOrEmpty(commandKey))
throw new ArgumentException("commandKey");
//something
}
This is exactly what Microsoft does if you look through the framework source code, so I suspect it is perfectly valid.
It is perfectly fine if you validate inside a constructor and throw exception if something goes wrong.
Related
I created my own class library and I have create() method like this:
public int create()
{
try
{
if(path!=null){
//do somethings
}
else{
throw new ArgumentNullException("path cannot be null ro empty", "path");
}
catch{
throw;
}
return 0;
}
}
In another project, I add my class library DLL and when I use my library method and because of something for example path=null my method thrown an exception and I get that in line that I wrote throw inside the catch...
I don't want that,how can I get error in line that I call create() method in my project
Thank you
SORRY I DONT KNOW ENGLISH VERY WELL so i try again to say my mean
I try to create class library and I want to get it to some one else to use, I want when exception in my create() method thrown visual studio highlight the line that create method was called, but it open my dll and go to create method and highlight the line that I wrote throw;... how can I solve it?
....................................................................................
finally I found the answer,see this link:
Hiding code from a DLL while debugging
To stop the debugger at the correct line when you throw your exception, all you have to do is to remove your try catch block (which is completely unnecessary in your case either way):
public int create()
{
if(path==null)
throw new ArgumentNullException("path", "path cannot be null or empty");
// do something
return 0;
}
Also as Oscar pointed out, you should switch the arguments when throwing the exception, as the first parameter is for the parameter name, the second for the message.
You have swapped the arguments of ArgumentNullException constructor. First goes the param name, and later the message.
public ArgumentNullException(
string paramName,
string message
)
http://msdn.microsoft.com/es-es/library/k8a0dfcy(v=vs.110).aspx
Also, you can safely remove the catch clause, as you're doing nothing there. Only catch exception you suppose to handle somehow, otherwise, let it bubble up.
When you rethrow an exception, only one stack frame is saved inside each method, therefore, you can't find out which line threw the exception, only the line that rethrew it. You can either log the message when you catch it for the first time, or don't rethrow but instead throw a new exception, and supply the caught exception as an inner exception.
You can always do check before try :
public int create(){
if(path!=null){
try{
//do somethings
}
catch{
throw;
}
else{
throw new ArgumentNullException("path cannot be null ro empty", "path");
}
return 0;
}
I have such method:
public function someMethod($param1 = null, $param2 = null)
{
...
if ($param1 == null &&...)
{
throw new Exception("Some parameter is wrong", 601);
}
}
Is it a good practice to include dynamic data in the Exception msg, since I have the exception code ? For example the exception could look like this:
throw new Exception("First parameter is wrong. You passed: {$param1}", 601);
What is your opinion, is it okey messages to be dynamic or I should stick to fixed text for the Exception messages ?
Should exceptions contain dynamic data?
Should? No. but they can! but be sure that "generating" this dynamic data will not cause another exception.
But you should never throw new Exception(). Extend it for your own custom exceptions or use javas exceptions like IllegalArgumentException
I found that exception message can't be null in C#, and after trying this
var ex = new Exception(null);
Console.WriteLine(ex.Message);
I get the following message:
Exception of type 'System.Exception' was thrown.
But, in this case,
var ex = new Exception(string.Empty);
Console.WriteLine(ex.Message);
the message is just empty.
How this can be explained? Do you think this is expected behavior?
The other answers (not including the answer from chopikadze) seem to be based on a misreading of the facts. Neither example is throwing an exception.
Rather, in the first example, the constructed exception ex is providing a message because the value of the constructor's message parameter was null. The message is "an exception of type 'System.Exception' was thrown".
It's a fairly common practice to have some fallback behavior when an object reference is null, so that's "how it can be explained". Whether it is "expected", of course, depends on your expectations.
Throwing exceptions in the course of handling exceptions can be problematic, so the framework designers must have chosen this behavior to reduce this possibility. It would have been a nightmare, frankly, if we all had to cover the possibility that exception messages might be null.
EDIT
The behavior is also documented in the remarks for the Message property: "If no message was supplied to the constructor for the current instance, the system supplies a default message that is formatted using the current system culture."
I looked in the CLI spec and in the C# spec, and I found no mention of a requirement that Message have a non-null return value, so I guess that supports the view that this behavior is a framework design decision.
Actually constructor doesn't need string, you can absolutely surely use null. This is reflectored part of Exception class:
internal string _message;
public Exception(string message)
{
this.Init();
this._message = message;
}
private void Init()
{
this._message = null;
this._stackTrace = null;
this._dynamicMethods = null;
this.HResult = -2146233088;
this._xcode = -532462766;
this._xptrs = IntPtr.Zero;
this._watsonBuckets = null;
this._ipForWatsonBuckets = UIntPtr.Zero;
this._safeSerializationManager = new SafeSerializationManager();
}
public virtual string Message
{
[SecuritySafeCritical]
get
{
if (this._message != null)
{
return this._message;
}
if (this._className == null)
{
this._className = this.GetClassName();
}
return Environment.GetRuntimeResourceString("Exception_WasThrown", new object[] { this._className });
}
}
So if you use null as message in constructor, localized string like "Exception of type 'System.Exception' was thrown." will be used as Message. It means - there is still your Exception, not another one, but it's property Message returns another (calculated) value instead of null from constructor.
I think that it's defined by design (and maybe is used in another places) that Exception.Message should be always not null. So if we want to allow developers use default constructor for Exception class (for example, for using with reflection or for allowing to populate properties later) but we also want to has Message always not null - we should wrap Message with something. I think, one of the possible place of Message usage is default dialog box showed after exception occurs. This way there could be used just Message property, instead of checking - is Message property equals to null etc.
string.Empty is not null it is a constant for "".
Your first example is giving a default message, your second example is an empty string
Yes, the constructor you are using requires a string. String.Empty is not the same as null therefore it will throw an exception.
http://msdn.microsoft.com/en-us/library/system.exception.aspx
Hi I wanted to ask because I'm not sure if is it propriete using of Exception:
public int Method(int a, int b) {
if(a<b) throw new ArgumentException("the first argument cannot be less than the second");
//do stuff...
}
can I throw Exception after if statement? or should I always use try - catch when it goes with the exceptions?
That is perfectly valid. That is exactly what exceptions are used for, to check for "Exceptions" in your logic, things that weren't suppose to be.
The idea behind catching an exception is that when you pass data somewhere and process it, you might not always know if the result will be valid, that is when you want to catch.
Regarding your method, you don't want to catch inside Method but infact when you call it, here's an example:
try
{
var a = 10;
var b = 100;
var result = Method(a, b);
}
catch(ArgumentException ex)
{
// Report this back to the user interface in a nice way
}
In the above case, a is less than b so you can except to get an exception here, and you can handle it accordingly.
In this case, you don't want to catch the exception. You're throwing it to alert the caller that they've made a mistake in the way they called your method. Catching it yourself would prevent that from happening. So yes, your code looks fine.
That's perfectly fine. You're throwing the exception, not catching/handling it, so you wouldn't need a try/catch block for it.
This is perfectly valid, you can use the same construct even with the constructors.
But What you should not do is
public int Method(int a, int b)
{
try
{
if (a < b)
throw new ArgumentException("the first argument cannot be less than the second");
}
catch (Exception)
{
}
return 0;
}
You've got the right idea. You could use your code like this:
void MyMainMethod()
{
// ... oh, let's call my Method with some arguments
// I'm not sure if it'll work, so best to wrap it in a try catch
try
{
Method(-100, 500);
}
catch (ArgumentException ex)
{
Console.WriteLine(ex.Message);
}
}
public int Method(int a, int b)
{
if (a < b) throw new ArgumentException("the first argument cannot be less than the second");
//do stuff ... and return
}
It might help to look through MSDN's Handling and Throwing Exceptions and Best Practices for Handling Exceptions
What you've done here is perfectly Ok.
A common pattern for arg checks is to wrap the check/throw code in a static "Contract" class ensuring you have a consistent approach to exception management when validating input arguments.
Slightly off topic but if using .NET 4.0 you can also look at the new Code Contracts feature for validation of method input and output.
All above answers are correct but I like to mention one additional point here which I did not see mentioned in any of the answers. The reason why you should throw an exception and not return an integer e.g. 0 or -1 for signalling that an error occurred, is that the returned integer can be mistakenly treated/assumed as a valid result of your method. It is an integer anyway, and your method, after performing its internal logic returns an integer. So the caller of this method can mistakenly treat any returned integer as a valid result, which can lead to bugs down the line. In that case, throwing an exception makes perfect sense.
I want to make a method, that throws a specific exception, by a parameter I give to the method. I have 3 userdefined exceptions, so instead of having to throw them every time I want to use them I want to make a method that handels it, so the parameter I give with my method is the exception I want to throw, but how do I do that?
I want to do something like this, but I am not really sure how to do it.
private void ExceptionMethod(custom exception)
{
try
{
//code that might fail
}
catch(exception ex)
{
throw new exception given by parameter(parameters from the exception);
}
}
FWIW I don't think this is a particulary good idea. Really, just throw your exception where it occurs, future maintainers of the code will thank you. (or at least not curse you)
If you have to do this thing, then its probably a better idea to pass an enumeration that you can switch on rather than the exception itself, then simply write a case statement to throw the exception you want.
Apart from the fact that this sounds like a bad idea, you can try the following:
private void TryElseThrow<TCustomException>(Action codeThatMightFail)
where TCustomException : Exception
{
try
{
codeThatMightFail();
}
catch (Exception e)
{
// Since there isn't a generic type constraint for a constructor
// that expects a specific parameter, we'll have to risk it :-)
throw
(TCustomException)Activator
.CreateInstance(typeof(TCustomException), e);
}
}
Use like so:
TryElseThrow<MyCustomException>(
() =>
{
throw new InvalidOperationException();
}
);
You were actually quite close:
private void ExceptionMethod(Exception customException)
{
try
{
//code that might fail
}
catch(Exception ex)
{
throw customException;
}
}
Will work, though I wouldn't recommend it for two reasons:
Catching Exception is a bad idea - you should just catch the exceptions that your code raises.
It's not a very good design (as others have pointed out).
So i dont see any problem in that.. as you say you already have your Custom Exception Written then you can do it like this.
in your parameter:
private void ExceptionMethod(CustomException myexception)
in catch:
throw myexception;
though its not a good Coding Design
Wouldn't it just be:
private void ExceptionMethod(MyCustomException exception)
{
try
{
//code that might fail
}
catch
{
throw exception;
}
}