if you think there is a possibility of getting a null pointer exception, should you use an if statement to make sure the variable is not null, or should you just catch the exception?
I don't see any difference as you can put your logic to deal with the null pointer in the if statement, or in the catch block, so which one is best practise?
The main Question is if it is a good idea to have methods returning Null at all, personally i do not have any problem with this, but as soon as you try to access modifiers of an object returned from this method and you forget to check if it is assigned this becomes an issue.
Ken has a good answer about this:
See this disscussion abou tthis issue:
Some further reading:
No Null Beyond Method Scope
Should We Return Null From Our Methods?
Well. Exceptions are just that. Exceptions. They are thrown when something unforseen has happened and should not be part of the normal program flow.
And that's what is happening here. You expected the argument to be specified when it's not. That is unexpected and you should therefore throw your own exception informing the user of that. If you want to get bonus points you can also include the reason to WHY the argument must be specified (if it's not obvious).
I've written a series of posts about exceptions: http://blog.gauffin.org/2013/04/what-is-exceptions/
using try catch for the statements is not an good idea. because when you use try catch them it seems that if some error comes the code will not turninate the application. but if you are sure about what kind of error can come you can tap the error at that point. that will not produce any unknown errors. for example.
here i am going to use the name variable and i am sure that this will throw Null Refrance Error .
This is not a good practice while you can handle this kind of error and make your code more readable. like.
Its always better to use Try Catch other than if else Here Exceptions are two types namely handled and UN-handled exceptions Even if u want to handle some function when the Exception u can handle it...
Handled exception always allows you to write some implementations inside the Catch block Eg. An Alert Message, A new Function to handle when such exception occurs.