I am displaying countries and it's codes using Locale.class.
I just want to know How is the exception handled in the follwing code
public Locale(String language, String country, String variant) {
if (language== null || country == null || variant == null) {
throw new NullPointerException();
}
baseLocale = BaseLocale.getInstance(convertOldISOCodes(language), "", country, variant);
localeExtensions = getCompatibilityExtensions(language, "", country, variant);
}
as I'm not catching it in my class
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode); //NullPointerException - thrown if either argument is null.
System.out.println("Country Code = " + obj.getCountry()
+ ", Country Name : " + obj.getDisplayCountry());
}
As I know the method has to use throws to throw any new Thowable object and the newly throwned object must be handled in the implemented class.
I'm a Newbie with exception handling in java.
Per the NullPointerException Javadoc, it extends RuntimeException. And per the RuntimeException Javadoc,
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.
In your example, if you trigger that NullPointerException your JVM will terminate and display a stack trace.
Related
I learning exception handling in JAVA, I found that exceptions/errors can also be classified on the basis of who throws or raises it.
Exceptions raised by JVM
Exceptions raised by API developer/programmer
My question is who is responsible for raising AssertionError?
The responsibility lies at the programmer regardless of whether they use, e.g.
throw new AssertionError("unreachable code");
or
assert condition;
Note that the assert statement is so called “syntactic sugar”.
When you write
class ClassWithAssert {
public ClassWithAssert() {
assert toString() != null;
}
}
It gets compiled to the equivalent of
class ClassWithAssert {
static final boolean $assertionsDisabled
= !ClassWithAssert.class.desiredAssertionStatus();
public ClassWithAssert() {
if(!$assertionsDisabled && toString() == null)
throw new AssertionError();
}
}
So the implicit throwing is not different to the explicit one, technically.
With a code like this
public static void main(String[] args) {
Exception one = new Exception("my cause");
System.out.println("A) " + one.getMessage());
System.out.println();
Exception two = new Exception(one);
System.out.println("B) " + two.getMessage());
System.out.println("C) " + two.getCause().getMessage());
System.out.println();
Exception three = new Exception("my message", one);
System.out.println("D) " + three.getMessage());
System.out.println("E) " + three.getCause().getMessage());
System.out.println();
Exception fourth = new Exception(null, one);
System.out.println("F) " + fourth.getMessage());
System.out.println("G) " + fourth.getCause().getMessage());
}
The output is this one
A) my cause
B) java.lang.Exception: my cause
C) my cause
D) my message
E) my cause
F) null
G) my cause
See the difference between B and F
In both cases I did NOT provided a message, but the difference is that in the B case the null value is not forced.
It seems that for the B case, when a message is not specified, the getMessage() method provides the format
className: cause.getMessage()
But I would except to have a null value (as is for the F case).
Is there a way to get null value (like F) if I call the getMessage on an Exception that has been created providing only the cause and not the message?
Take a look at Exception's JavaDoc. For the constructor that takes only a Throwable:
Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException).
So, in your B case, since the cause is not null, you get the value of cause.toString() as the container exception's message.
If that constructor was used to create the exception, then by the time you catch the exception, it's too late - it already has a detail message as specified above. You can't get the "null" as the detail message is not null. You can compare it to the cause's toString() and deduce that it should have been null, but that's a kludge and theoretically, the cause's message could change over time and be different at the time of the catch.
Basing on #RealSkeptic reply I created a method like this
public static String getMessageOrNull(Throwable t) {
String message = t.getMessage();
if (t.getCause() != null && message.equals(t.getCause().toString())) {
message = null;
}
return message;
}
It may not be the best approach but for my case works just fine.
You could simply build it the same way, hiding it in a static method :
public static Exception getException(Throwable cause){
return new Exception(null, cause);
}
Or you define your own class that will use the Exception(String, Throwable) constructor like
public MyExceptoin extends Exception{
public MyException(Throwable cause){
super(null, cause);
}
}
This would be simpler to use later.
Is it better to wait for a null pointer exception to happen?
public void doSomething(String str) {
Double val = Double.parseDouble(str); // Null pointer exception thrown here
// Other code
}
Or is it better to check every time for it, as early as possible?
public void doSomething(String str) {
if (str == null)
throw new NullPointerException(); // Null pointer exception thrown here
Double val = Double.parseDouble(str); // Other code
}
I would recommend using an assert clause. I think his response best answers your question
Avoiding != null statements
I would indicate in your method if str can be null or not with the #Nullable keyword. If you are disallowing the str variable to be null then do not do any null checking. You should instead check if str is null before calling doSomething. If str is allowed to be null then wrap it in a null check and do whatever you deem to be appropriate if the variable is null.
public void doSomething(#Nullable String str) {
if (str != null) {
Double val = Double.parseDouble(str);
// other code
}
else {
// return or do something else
}
}
Or..
public void doSomething(#Nullable String str) {
if (str == null) {
return;
}
Double val = Double.parseDouble(str);
// other code
}
I would not recommend throwing a null pointer error unless the application cannot continue without the str variable. You want to capture exceptions so your application doesn't crash not allow them to crash your application.
In that case it doesn't make much difference as parseDouble will throw a NPE. In a more general case, since Java 7, you can use:
Objects.requireNonNull(str); //throws NPE if str is null
//rest of the code
There no different code. You should throw some specific exception.
And sometimes null is legal value.
Sometimes it is usual to define something like a method contract.
I am doing this via Spring Asserts:
org.springframework.util.Assert;
Assertion utility class that assists in validating arguments. Useful
for identifying programmer errors early and clearly at runtime.
For example, if the contract of a public method states it does not
allow null arguments, Assert can be used to validate that contract.
Doing this clearly indicates a contract violation when it occurs and
protects the class's invariants.
Typically used to validate method arguments rather than configuration
properties, to check for cases that are usually programmer errors
rather than configuration errors. In contrast to config initialization
code, there is usally no point in falling back to defaults in such
methods.
This class is similar to JUnit's assertion library. If an argument
value is deemed invalid, an IllegalArgumentException is thrown
(typically).
In your case:
public void doSomething(String str) {
Assert.notNull(str);
Double val = Double.parseDouble(str); // Nullpointer not possible here if the contract was not injured.
// Other code
}
If a null value is passed by any developer the contract was not fullfilled and a IlligalArgumentException is thrown.
Easy testable via Junit:
/**
* Check case that passed string is null.
*/
#Test(expected = IllegalArgumentException.class)
public void testDoSomething_StringIsNull() {
mClassUnderTest.doSomething(null);
}
I implemented a class:
public class TableInfoGroup {
Vector<TableInfo> tableInfoVector;
public TableInfoGroup(Vector<String> tableNameVector, Vector<String> tableTagIdVector)
{
if (tableNameVector.size() != tableTagIdVector.size())
return;//I think it's not proper to do this
tableInfoVector = new Vector<TableInfo>();
for(int i = 0; i < tableNameVector.size(); i++)
tableInfoVector.add(new TableInfo(tableNameVector.get(i), tableTagIdVector.get(i)));
}
}
How to do that elegant? Throws a exception? Thanks.
Personally, I would make the method throw an IllegalArgumentException:
Thrown to indicate that a method has been passed an illegal or inappropriate argument.
For example:
if (tableNameVector.size() != tableTagIdVector.size())
throw new IllegalArgumentException("tableNameVector and tableTagIdVector " +
"must have the same size");
Even though IllegalAgumentException is an unchecked exception, I would still add it to the method's throws clause as documentation.
Making a constructor throw an exception will prevent the object from the being constructed, which I would argue is the correct course of action in this case.
I have two constructors for my class, one that takes File object and the other takes a String object, and I want to use the this keyword. The function with the implementation is the one with File as parameter, and the one with String will call this. Now I want to check for exception in the constructor that takes String but I get error, that this should be the first line. How can I check for errors then call this.
Here is my code:
public Test (String filename) {
if (filename == null)
throw new NullPointerException("The String you entered is null.");
if (filename.isEmpty())
throw new IllegalArgumentException("The String you entered is empty.");
this(new File(filename)); // error
}
public Test (File f) {
/* implementation here */
}
This is the exact error: Constructor call must be the first statement in a constructor
Unfortunately, this is impossible in Java thanks to their arbitrary restrictions. You have two main possibilities.
The more idiomatic Java technique is to wrap everything in a factory function so you can catch the exception. Factory functions are also useful because they let you create objects polymorphically, and help hide the details of what object is actually created.
public static Test create(String filename){
if (filename == null)
throw new NullPointerException("The String you entered is null.");
if (filename.isEmpty())
throw new IllegalArgumentException("The String you entered is empty.");
return new Test(filename);
}
private Test (String filename) {
this(new File(filename));
}
public Test (File f) {
/* implementation here */
}
The other option is to write the constructor in bytecode, where there are no such restrictions present. Unfortunately, bytecode is less readable and maintainable, so you'll probably want to minimize the amount of bytecode in a primarily Java app. You might also be able do this in a non Java language like AspectJ.
Edit: If you're not actually trying to catch the exceptions, then there's a third possibility. You can insert arbitrary code before the super constructor call by creating a separate function which performs the checks and then passing it as a dummy argument to the super constructor call. Since arguments are evaluated first, your code will run first, but this is a bit of a hack.
public Test (String filename) {
this(doChecks(filename), new File(filename));
}
private static Void doChecks(String filename){
if (filename == null)
throw new NullPointerException("The String you entered is null.");
if (filename.isEmpty())
throw new IllegalArgumentException("The String you entered is empty.");
return null;
}
public Test (Void dummy, File f) {
this(f);
}
public Test (File f) {
/* implementation here */
}
In case we use this or super in constructor, either this or super should be the first statement in the constructor. It is better, if you throw exception from a particular constructor.
public Test (String filename) {
this(new File(filename));
}
Let the second constructor handle any exception, caused by passing null.
public Test (File file) {
// exception handling code
// or new instance creation
}
No, you cannot check for errors before call this. It's forbidden by the specification. In fact, you didn't need it. Let new File(filename) to throw exceptions.
edit: I saw aizen92's comment: Actually that is what my constructor with the implementation has, it catches the exception may be thrown by file, so I just add the null exception and use this directly in my second constructor?
public Test (String filename) {
this((filename == null || filename.isEmpty()) ? null : new File(filename));
}