Why static methods will not throw NullReferenceException? or will it throw NullReferenceException? If it will not throw the error, can anyone explain why with relevant example.
Static methods don't relate to an instance of the type, so there's no reference to potentially be null.
Of course, if the body of a static method does something which will normally throw an exception, it will be propagated as usual:
class Test
{
static void Main()
{
GoBang();
}
static void GoBang()
{
string s = null;
int y = s.Length; // Bang! NullReferenceException
}
}
Static method are called with class which is never null. Instance methods are called with instance which can be null as the programmer did not do new on it.
The CLR considers any type to be unstable if it throws an unhandled exception (of any kind) in a type constructor. Attempting to access any member of the unstable type will cause a TypeInitializationException to be thrown.
So, NullReferenceException will be thrown but is marshalled into the TypeInitializationException by the runtime.
Related
I am trying to implement an audit trail on MVC project , by overriding the context by adding another peice of functionality (to so the audit).
The overriding of SaveChanges works fine, however the problem I have is with SaveChangesAsync.
Here is part the code from the context
public override Task<int> SaveChangesAsync()
{
throw new InvalidOperationException("User ID must be provided");
}
public override int SaveChanges()
{
throw new InvalidOperationException("User ID must be provided");
}
public async Task<int> SaveChangesAsync(int userId)
{
DecidSaveChanges(userId);
return await this.SaveChangesAsync(CancellationToken.None);
}
public int SaveChanges(int userId)
{
DecidSaveChanges(userId);
return base.SaveChanges();
}
The problem I have is with my controller
await db.SaveChangesAsync(1);
1 being a dummy user. I get the following error.
Error 1 The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.
do you know what I am doing wrong here? and how to fix it?. I am using EF6 and MVC5
do you know what I am doing wrong here?
Yes, just look at your compiler error message:
The 'await' operator can only be used within an async method.
So, the controller action (that contains the call to SaveChangesAsync(1)) needs to be async.
and how to fix it?
Yes, just look at your compiler error message:
Consider marking this method with the 'async' modifier and changing its return type to 'Task<System.Web.Mvc.ActionResult>'.
So, you fix it by making the controller action async and changing its return type from ActionResult to Task<ActionResult>.
I'm just trying to stub the method but getting null pointer exception. I'm kinda blank what's going on here.
my method :
OauthStatus validate(HttpServletRequest request,
boolean accessTokenRequired) throws OauthProviderException;
and Stub is :
Mockito.when(oauthProviderMock.validate((MockHttpServletRequest) Mockito.anyObject(), (boolean)Mockito.anyBoolean())).
thenReturn(new OauthStatus());
i see there is no wrong in mocking but throws nullpointer exception.
Any idea what's going on here?
Remove your casts to (MockHttpServletRequest) and (boolean) so it looks like this
Mockito.when(oauthProviderMock.validate(Mockito.any(HttpServletRequest.class), Mockito.anyBoolean())).
thenReturn(new OauthStatus());
According to the anyObject API it will return null so you are probably seeing your NPE here.
According to the anyBoolean API it will return false so there should be no need to cast.
Work around is Mocked the method through programmatically by using anonymous class instead of Mockito.
ex:
oauthProvider = new OauthProvider(){
validate( HttpServletRequest req, boolean flag) throws Exception{
throw new RuntimeException();
}
};
I'm messing around with Eclipse(and java in general) for the first time in about a year. among the things I have forgotten is the following:
I have a function (void callvote() that I am hoping will be activated by my main function (that is, automatically, relatively early in the program). I currently have it within the same class (body) as the main function itself.
I try to call it withcallvote(); and get an error, "- Cannot make a static reference to the non-static method callvote() from the type body"
my function callvote is, at the moment, in the space below main and simply says
public void callvote()
{
}
am i committing a horrible sin by putting more functions in the same class as main?
is this a relatively easy fix that I missed somehow?
What does this error mean?
Have I woken Azatoth with this code?
Thanks in advance,
Tormos
Without the static modifier callvote is implicitly an instance method - you need an instance of a class to call it.
You could mark it as static also:
public static void callvote() ...
Or create an instance of the declaring class:
MyClass instance = new MyClass();
instance.callvote();
main() is a static method, meaning you can call it directly from a class whereas non-static members can only be called from an object. In order for you to call the callvote() method you need to first instantiate an object of your class:
public static void main(String [ ] args) {
MyClass myObject = new MyClass();
myObject.callvote();
}
Another way to avoid the error is to make you callvote() method static as well, but it's usually not what you want to do (but it depends on the nature of your class and method).
This post describes some of the dangers with the overuse of static methods: Class with single method -- best approach?
Try this:
public class Main {
public static void main(String[] args) {
new Main().callvote()
}
}
the main() entry point of your java program is static. You cannot call a non static method from a static one.
So you have to instanciate your Class first and call the method after.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
StatusCodeException Vs. RuntimeException in GWT
I want to trigger RPC callback "onFailure" if the session expires in the server.
I created a custom RPC AsyncCallback that handles the "session expired" event from the server.
I overrode RemoteServiceServlet to validate the session prior to invoking the method. So basically, it is not the declared method that throws the exception but the custom RemoteServiceServlet. It still goes to the "onFailure" in the client async but the Throwable object is still of type "StatusCodeException" without the EXPIRED_SESSION_MSG message. Any ideas?
Custom RemoteServiceServlet:
public class XRemoteServiceServlet extends RemoteServiceServlet {
private final static String EXPIRED_SESSION_MSG = "ERROR: Application has expired session.";
#Override
protected void onAfterRequestDeserialized(RPCRequest rpcRequest) {
HttpServletRequest httpServletRequest = this.getThreadLocalRequest();
HttpSession session = httpServletRequest.getSession(false);
if (session != null) {
final String sessionIdFromRequestHeader = getSessionIdFromHeader();
if (!isNullOrEmptyString(sessionIdFromRequestHeader)) {
final String sessionId = session.getId();
if (!sessionId.equals(sessionIdFromRequestHeader)) {
throw new RuntimeException(EXPIRED_SESSION_MSG);
}
}
Custom AsyncCallback:
public class XAsyncCallback<T> implements AsyncCallback<T> {
private final static String EXPIRED_SESSION_MSG = "ERROR: Application has expired session.";
#Override
public void onFailure(Throwable caught) {
final String message = caught.getMessage();
if (!isNullOrEmptyString(message) && message.contains(EXPIRED_SESSION_MSG)) {
com.google.gwt.user.client.Window.Location.reload();
}
}
#Override
public void onSuccess(T arg0) {
}
/**
* Returns true if the string is null or equals to the empty string.
*
* #param string the string to test
* #return true if the string is empty
*/
private static boolean isNullOrEmptyString(String string) {
return string == null || "".equals(string);
}
}
See here for handling exceptions with GWT RPC.
An "expected failure" is an exception thrown by a service method that is declared in the signature of the service method. These exceptions are serialized back to the client.
"Unexpected expections" are errors that are not part of the service method's signature, or that result from SecurityExceptions, SerializationExceptions, or other failures within the RPC framework.
What you want is a checked exception, because you want to send it back to the client and do something about it. The RPC framework is in charge of catching it, serializing it and calling the onFailure method with the right exception. In order to do that, you need to follow its guidelines which are :
You need to specifiy in the service
signature that the exception can be
thrown.
The exception must be thrown
in the service implementation method.
What you're doing is throwing an unexcepted exception from some method that shouldn't even be throwing exceptions. So RPC doesn't know what really happened and sends back a generic message saying 'Hey, something unexpected happened, look at the server log'.
I understand that you want to check the session on every call. Your easiest option is to have a method to check that in your servlet implementation and call it from all your service methods.
Otherwise, you can try to override the GWT RPC framework by looking at the class
com.google.gwt.user.server.rpc.RPC
but that's pretty advanced stuff.
If you want to send exceptions via GWT-RPC you must use checked exceptions. RuntimeException is an unchecked exception so you can not use it in this case.
Create your own exception that extends Exception and implements Serializable. Also, you must indicate on methods declaration that this method might throw an exceptions:
Not sure what exactly is going on here, but seems like in .NET 1.1 an uninitialized event delegate can run without issues, but in .NET 2.0+ it causes a NullReferenceException. Any ideas why. The code below will run fine without issues in 1.1, in 2.0 it gives a NullReferenceException. I'm curious why does it behave differently? What changed?
Thanks
eg
class Class1
{
public delegate void ChartJoinedRowAddedHandler(object sender);
public static event ChartJoinedRowAddedHandler ChartJoinedRowAdded;
public static DataTable dt;
public static void Main()
{
dt = new DataTable();
dt.RowChanged += new DataRowChangeEventHandler(TableEventHandler);
object [] obj = new object[]{1,2};
dt.Columns.Add("Name");
dt.Columns.Add("Last");
dt.NewRow();
dt.Rows.Add(obj);
}
private static void TableEventHandler(object sender, DataRowChangeEventArgs e)
{
ChartJoinedRowAdded(new object());
}
}
[updated] AFAIK, there was no change here to the fundamental delegate handling; the difference is in how DataTable behaves.
However! Be very careful using static events, especially if you are subscribing from instances (rather than static methods). This is a good way to keep huge swathes of objects alive and not be garbage collected.
Running the code via csc from 1.1 shows that the general delegate side is the same - I think the difference is that the DataTable code that raises RowChanged was swallowing the exception. For example, make the code like below:
Console.WriteLine("Before");
ChartJoinedRowAdded(new object());
Console.WriteLine("After");
You'll see "Before", but no "After"; an exception was thrown and swallowed by the DataTable.
The eventhandler system is basically just a list of functions to call when a given event is raised.
It initializes to the "null" list, and not the empty list, so you need to do
if (ChartJoinedRowAdded != null)
ChartJoinedRowAdded(new object())
The way events work hasn't really changed from 1.1 to 2
Although the syntax looks like normal aggregation it really isn't:
dt.RowChanged += TableEventHandler;
dt.RowChanged += null;
dt.RowChanged += delegate (object sender, DataRowChangeEventArgs e) {
//anon
};
Will fire TableEventHandler and then the delegate - the null is just skipped.
You can use null to clear events, but only inside the event firing class:
this.MyEvent = null;
If nothing subscribes your event will be null - see soraz's answer. The DataTable class will contain a similar check and won't fire the event if there are no subscribers.
The standard pattern is:
//events should just about always use this pattern: object, args
public static event EventHandler<MyEventArgs> ChartJoinedRowAdded;
//inheriting classes can override this event behaviour
protected virtual OnChartJoinedRowAdded() {
if( ChartJoinedRowAdded != null )
ChartJoinedRowAdded( this, new MyEventArgs(...) );
}