java handle return exception - java

The following code is supposed to return the last value in arraylist if it has one, if not, how could I return the exception?
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
}
}
arrl here is ArrayList
I excuted above code and received "error: missing return statement"

You have return statement in your try{} but not in your catch(){}, this gives you the exception. You can include the return in both or return after the try catch.
public int getLast() {
Object o=null;
try {
o=arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
}
return o;
}
Also to return the exception back to the caller you need to rethrow it from your method, or not catch it at all
catch (Exception e) {
System.out.println("Caught "+ e);
throw e;
}
or
public int getLast() {
return arrl.get(arrl.size() - 1);
}
But I doubt any exception being thrown from this statement except for IndexOutOfBoundsException

You don't return an exception.. You throw it back to the caller.
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
throw e;
}
}
Your code gives you compilation error because you are not returning anything in catch block. throwing would be good enough.
Alternatively, don't catch it, any uncaught exceptions will be automatically thrown back to the caller. So below code would also throw the exception back to the calling method.
public int getLast() throws Exception {
return arrl.get(arrl.size() - 1);
}

There's really no good reason for the try/catch block here at all. Just let the NPE or AIOOBE be thrown to the caller and let him deal with them.

You are getting this error because if the first return in the try-part didn't work the compiler doesn't know what it should return instead. You need either another return or exception rethrow in the catch-part:
public int getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (Exception e) {
System.out.println("Caught "+ e);
// You need to return something here or rethrow the e...
}
// or return something here.
}
...but this kind of logic is bad any way and this function shouldn't throw exceptions at all. I'd be better to check it the array has any items before getting the last one. If you run this in a loop the performace might be really bad if the error is thrown frequently.
public int getLast() {
if (arrl != null && arrl.size() > 0) {
return arrl.get(arrl.size() - 1);
}
else {
return -1;
}
}
or
public Integer getLast() {
if (arrl != null && arrl.size() > 0) {
return arrl.get(arrl.size() - 1);
}
else {
return null;
}
}

In this scenario, the only exceptions that may be raised are NPE due to arrl being null and an indexing error if the list is empty. If the class is properly initialised, the NPE shouldn't happen at all. The other exception is a client error, which may be passed on to the caller. Alternatively, one might consider returning null (after changing int to Integer):
public Integer getLast() {
try {
return arrl.get(arrl.size() - 1);
} catch (IndexOutOfBoundsException ioobe) {
return null;
}
}

There is the possability that your method can not return a value (for what reasons ever). In this case you should use now java.lang.Optional (Java-8) as return type:
public Optional<Integer> getLast() {
try {
return Optional<T>.ofNullable(arrl.get(arrl.size() - 1));
} catch (Exception e) {
e.printStackTrace();
return Optional.empty();
}
}
This way you will force the user of your method to deal with the situation of not having a result to be returned. (BTW: you should not catch Exception, mostly never. Instead take care that arrl is not null and arrl.size() is within the limits. Handling exceptions is for the... umm exeptional cases, not to be used as control statement.)

Related

How does Validation.Exception in Java work?

I am quite new to Java and I am struggeling to understand Exceptions.
In an Excercise I was supposed to implement the Interface "exceptions.excercise.Validator" in the class "ValidatorImpl" and the Method "User#validate".
I am struggeling to understand what exactly is happening in these lines of codes and I would really appreciate it, if somebody could help me :):
I am not sure if you need the whole java project to understand the code but here's what I don't really understand:
*In User.java
public void validate() throws UserException {
Validator valid = new ValidatorImpl();
try {
valid.validateAge(this.getAge());
valid.validateEmailWithRuntimeException(this.getEmail());
} catch (ValidationException e) {
throw new UserException("age is incorrect", e);
} catch(ValidationRuntimeException e ) {
throw new UserException("mail is incorrect", e);
}
}
In ValidatorImpl.java:
package exceptions.excercise;
public class ValidatorImpl implements Validator {
#Override
public void validateAge(int age) throws ValidationException {
if ((age < 0) || (age > 120)) {
throw new ValidationException(age + "not betweeon 0 and 120");
}
}
#Override
public void validateEmailWithRuntimeException(String email) {
if (email == null) {
throw new ValidationRuntimeException("email is null");
}
if (!email.contains("#")) {
throw new ValidationRuntimeException("email must contain #sign");
}
}
}
I know this is quite a lot.
Thank you if you read all of this :)
First, you have a try-catch block. This will catch exceptions thrown in the try-part and if an exception is found they'll run the catch-block for the type of exception. The methods valid.validateAge(int) and valid.validateEmailWithRuntimeException(String) both can throw exceptions.
If the age is under 0 or over 120 validateAge will throw an ValidationException. The try-catch will catch that and will run the first catch-block, which will output a new UserExeption("age is incorrect").
If the age is valid, validateEmailWithRuntimeException will be called next.
This works the same way! If the Email is invalid, a ValidationRuntimeException will be thrown and catched. In this case, the second catch-block will be called and a new UserExeption("mail is incorrect") will be outputted.

Prettifying exception handling in function

Can this func. not be prettified?
Can the the catch clause be left empty, I have heard it's frowned up on.
apiClient.accountList() is where the exception can occur.
public Optional<Account> getAccount(String accountUuid) throws ApiException {
try {
for (Account account : apiClient.accountList()) {
if (account.getUuid().equals(accountUuid)) {
return Optional.of(account);
}
}
} catch (ApiException e) {
return Optional.empty();
}
return Optional.empty();
}
If you're very motivated to avoid the duplicate return statement, a simple tweak to the control-flow should do it. As mentioned in the comments, logging exceptions is often a good idea.
public Optional<Account> getAccount(String accountUuid) throws ApiException {
Optional<Account> result = Optional.empty();
try {
for (Account account : apiClient.accountList()) {
if (account.getUuid().equals(accountUuid)) {
result = Optional.of(account);
break;
}
}
}
catch (ApiException e) { /* Log exception */ }
return result;
}
You can use Stream, assuming getUuid does not throw an ApiException.
public Optional<Account> getAccount(String accountUuid) throws ApiException {
try {
return apiClient.accountList().stream()
.filter(account -> account.getUuid().equals(accountUuid))
.findAny();
} catch (ApiException e) {
/* Log exception */
return Optional.empty();
}
}
Actually instead of collection returning methods like accountList() it more and more makes sense to use Streams, accountStream().

Do you need a return type method to be handled in front end?

So I am trying to get more insight on Java methods as I am still new to all this. And in my method type I declared as below:
public int insert_url(long nodeid,String url,String startdt,String enddt,int enable) {
try {
// UrlLink attr = em.find(UrlLink.class,n);
String sql="INSERT INTO urllink(NODEID,URL,STARTDT,ENDDT,ENABLE) VALUES("+nodeid+",'"+url+"','"+startdt+"','"+enddt+"',"+enable+")";
em.createNativeQuery(sql).executeUpdate();
return 1;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
And in my front end, I called it simply like below:
try {
fileFacade.insert_url(nd.getNodeid(), "f0=" + nd.getNodeid() + "&ts=" + hash, currentDate, defaultDate, 1);
} catch (Exception e) {
// error should be handled
}
Initially, I was using void method rather than int. My question is if I am not using a return method,can it be handled in the front end?
In the even that the end user encounters any error, they ought to know an error occurred.

Catching Exception with JUnit #Test(expected=Exception.Class)

I am writing a test case using JUnit and I am trying to catch an Exception using #Test(expected=Exception.Class). For some reason I am unable to catch the exception. If I pass null it would throw NullPointerException and the test catches it because Exception is the parent class but on my Coverage report the exception is still not covered.
Method under test:
private static final String CONTENT_LENGTH = "Content-Length";
protected long getContentLength( MultivaluedMap<String, String> headers ) {
String length = headers.getFirst( CONTENT_LENGTH );
if( length != null ) {
try {
return Long.valueOf( length );
} catch( Exception e ) {}
}
return 0;
}
JUnit test case:
#Test(expected=Exception.class)
public void testGetContentLength() {
new TestBaseMessageBodyReader().getContentLength(null);
}
Any help would be appreciated.
Thanks
Catching generic exception is bad practice and even worse to catch an exception and do nothing. in your try catch you should catch NumberFormatException which is what Long.valueOf has the potential of throwing. Even then your jUnit will not never catch the exception because you are catching the exception but not doing anything with it, the method would always return 0 as it's currently written (provided you're not passing null)
Here is some code that would catch the exception on your unit test. I'd create two unit tests, one to catch your the first exception and one to catch the second.
protected long getContentLength(MultivaluedMap<String, String> headers)
{
if(null == headers)
{
throw new SomeCustomException("some message");
}
Long returnValue = 0;
String length = headers.getFirst(CONTENT_LENGTH);
try
{
returnValue = Long.valueOf(length);
}
catch (NumberFormatException e) {
// if you can recover handle it here
// if you can't recover then break the app
throw new SomeOtherCustomException("some other message");
}
return returnValue;
}

Null pointer exception in java ArrayList

I am just beginning java programming. I have got a Null Pointer exception problem in the array List
My code is below
ArrayList<Arpaymentitem> arpaymentitemsList= jb.getArpaymentitems();
arpaymentitemsList.removeAll(Collections.singleton(null));
try {
for(Arpaymentitem arpaymentitem:arpaymentitemsList)
{
if (arpaymentitem.getInvoicekey()!=null) {
statement2.setString(1,arpaymentitem.getInvoicekey());
}
if(arpaymentitem.getInvoicekey() != null)
{
statement2.setString(2,arpaymentitem.getAmount());
}
}
statement2.addBatch();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am getting null pointer exception error in the FOR statement. I am sure there are some null values in the list. To ignore the null values I have introduced a step
ArrayList<Arpaymentitem> arpaymentitemsList= jb.getArpaymentitems();
arpaymentitemsList.removeAll(Collections.singleton(null)); --> remove nulls
The NPE I got is
java.lang.NullPointerException
at payment.Intacct_Payment.main(Intacct_Payment.java:169) and the line is
for(Arpaymentitem arpaymentitem:arpaymentitemsList)
The problem still persists. What am I doing wrong here.
Can you try this follwing steps and give a feedback
ArrayList<Arpaymentitem> arpaymentitemsList = new ArrayList<>();
if (jb.getArpaymentitems().size()> 0)
{
for (Arpaymentitem arpaymentitem : jb.getArpaymentitems())
{
System.out.println("Description: ...");
arpaymentitemsList.add(arpaymentitem)
}
}
//The Rest of the code

Categories