Android unhandled exception error - java

I'm try to figure out this for a while, so I have a method that is calling a count() method that is suppose to throw and exception
the count() method
public int count() throws ParseException {
return something that may throw the ParseException
}
and then calling from here
ParseQuery<ParseObject> query = ParseQuery.getQuery(className);
query.fromLocalDatastore();
int result = 0;
try {
result = query.count();
} catch (ParseException e) {
result = 0;
}
return result;
Now I have been trying different scenarios but no matter what the IDE still not compiling and give me the following error
Error:(254, 11) error: exception ParseException is never thrown in body of corresponding try statement
Error:(253, 33) error: unreported exception ParseException; must be caught or declared to be thrown
in the line result = query.count();
I have no idea what I'm doing wrong, thanks for any help

You cannot catch exception that will never thrown by your try block as error suggested
try {
result = query.count(); // this statement not throwing ParseException
} catch (ParseException e) { // you are trying to catch ParseException that never gonna throw.
result = 0;
}
It is like
try {
.... code // throws ExceptionA
}
catch (ExceptionB e) { // and calling ExceptionB
}

Related

Junit not catching FileNotFoundException

I runt into something strange. I have a method to read from a CSV file, line by line. The method takes the filePath and in my JUnit test, I'm testing this method with the wrong filePath expecting to get a FileNotFoundException. The thing is that JUnit5 doesn't throw that exception but in the eclipse console I can see that the JVM throws that exception, so I'm struggling to understand why
I've set up my test code to throw the exception but it doesn't get thrown. I tried to catch Exception but still no joy.
Here is the method and the test method
public void readData(String COMMA_DELIMITER, String READ_FILE_PATH) {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(READ_FILE_PATH));
String line = "";
//Read to skip the header
br.readLine();
//Reading from the second line
while ((line = br.readLine()) != null)
{
String[] employeeDetails = line.split(COMMA_DELIMITER);
populateModel(employeeDetails);
}
//Lets print the Employee List
for(Employee e : empList)
{
System.out.println(e.getName() + "; " + e.getSurname() + "; " + e.getDateOfBirth() + "; " + e.getSex());
}
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Test
void testWrongFilePath() {
String READ_FILE_PATH_WRONG = System.getProperty("user.dir") + "/teest/XXXFile.csv";
System.out.println(READ_FILE_PATH_WRONG);
Assertions.assertThrows(FileNotFoundException.class, () -> {
readData.readData(COMMA_DELIMITER, READ_FILE_PATH_WRONG);
});
}
In the console, I get the FIleNotFOundException, but the output of the test says that
org.opentest4j.AssertionFailedError: Expected java.io.FileNotFoundException to be thrown, but nothing was thrown.
You cannot expect from your Assertion framework to catch an exception that is caught inside your SUT:
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You either have to :
Log then rethrow same / different exception and assert on that.
Make your method return Boolean as a success equivalent which you can then assert on.
You're catching the FileNotFoundException within readData.
Try refactoring so that you don't have a try-catch, and have public void readData(String COMMA_DELIMITER, String READ_FILE_PATH) throws IOException { ...
(FileNotFoundException is a subclass of IOException.)
assertThrows(Class<T> expectedType, Executable executable)
doesn't assert that an exception is thrown at a time in your code (which is the true in your case). But that asserts that the statement invoked in the Executable lambda throws an exception (which is false in your case).
Since you caught the FileNotFoundException in the method under test, the exception is never propagates to the lambda return and JUnit can only emit an error because the expected exception was not encountered.
To assert such a thing, don't catch the exception by removing the catch statement and instead of declare throws FileNotFoundException in the declaration of the tested method :
public void readData(String COMMA_DELIMITER, String READ_FILE_PATH) throw FileNotFoundException {...}
Your method doesn't throw FileNotFoundException: you catch it, print the stack trace, and carry on as if no exception occurred:
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JUnit isn't magic: it can't detect things that happen inside the method, other than by detecting side effects (values returned, uncaught exceptions, mutating state).

How to throw an Exception to the method caller inside a try catch body?

I am not able to throw a custom exception from within a try block. The exception doesn't return back to the caller, instead jumps out of the try-catch block and executes the remaining statements (return i; statement in the code).
I know that I don't need the try-catch block for the function "exceptionTester" to run. However I'd like to know the reason for this behaviour. exceptionTester(0) returns 0 instead of the exception being thrown.
public class Test {
public static int exceptionTester(int i) throws FAException{
try {
if (i==0) {
throw new FAException("some status code", "some message", null);
}
} catch (Exception e) {
// TODO: handle exception
}
return i;
}
public static void main(String[] args) {
try {
int in = exceptionTester(0);
System.out.println(in);
} catch (FAException e) {
System.out.println(e.getStatusCode());
}
}
}
public class FAException extends Exception {
private String statusCode;
public FAException(String statusCode, String message, Throwable cause){
super(message,cause);
this.statusCode = statusCode;
}
public String getStatusCode() {
return this.statusCode;
}
}
You are throwing a FAException and you want to re-throw it. Either remove the try-catch entirely, or catch that specific exception (if you insist) like
public static int exceptionTester(int i) throws FAException{
try {
if (i==0) {
throw new FAException("some status code", "some message", null);
}
} catch (FAException e) {
throw e; // <-- re-throw it.
}
return i;
}
It is also possible to throw a new FAException wrapping some other type of exception in the catch. Which might look like,
} catch (Exception e) {
throw new FAException("Status Code", "Original Message: " + e.getMessage(), e);
}
You are catching any exception that extends from Exception. FAException extends Exception so in your method exceptionTester(int) you are throwing FAException and immediatelly catching it. Since catch block does nothing, it continues in method processing. That's why return is reached.
If you want to catch any exception that can occur in method and rethrow it as your exception then:
public static int exceptionTester(int i) throws FAException{
try {
// some code that throws an exception
// e. g. dividing by zero, accessing fields of null object, ...
} catch (Exception e) {
throw new FAException("Ooops", "Something went wrong", e);
}
return i;
}
If you want to throw an exception when some criteria is met:
public static int exceptionTester(int i) throws FAException {
if (i == 0) {
throw new FAException("IllegalArgument", "arg can not be 0", null);
}
return i;
}
It is simply because you are not rethrowing the caught exception in the main method.
Even if you do this:
try {
if (i==0) {
throw new FAException("some status code", "some message", null);
}
} catch (Exception e) {
throw e; --> catching FAException and throwing it to the caller
// 'e' is of type FAException (though you caught it as Exception)
}
return i;
}
It should work, and you won't even hit the "return i" statement.
Otherwise (if no re-throwing, the catch statement will handle the exception and not the caller).
Rest, I agree with the above answer.

Why getting handle or declare error, when already declared?

This is the code sample and I am getting an error "must be caught or declare to
be thrown" but I have
already handled the IOException. So can you please tell why the error is populating. The code also
follows the handle and declare rule.
public void rethrow() throws SQLException, IOException {
try {
couldThrowAnException();
}
catch(Exception e) {
e = new IOException();
throw e; //Error: must be caught or declare to be thrown
}
}
The problem you are running into is that the compiler deals with the variable declaration type, not the type you assign to the variable.
The variable is of type Exception, which is not part of the throws clause.
If you change the catch() clause to match IOException, it will compile.
I'd suggest you read the Exceptions Trail of the Java Language Tutorial.
You handled IOException but you are throwing Exception(not IOException ) from catch block.
So you have to add Exception in throws clause
or
catch IOException instead of Exception in the catch block
public void rethrow() throws SQLException, IOException {
try {
couldThrowAnException();
}
catch(IOException e) {
e = new IOException();
throw e; //Error: must be caught or declare to be thrown
}
}
Although, it makes no sens to cathc it and throw it...
A far better way would be:
public void rethrow() {
try {
couldThrowAnException();
}
catch(IOException e) {
//do something when you encounter the io-error
}
catch(SQLException e) {
//do something when you encounter the sql-error
}
}

Catch handler for multiple exceptions?

I am experimenting with exceptions and i want to ask when it is possible to handle multiple exceptions in one handler and when it is not?
For example i wrote the following code which combines two exceptions (FileNotFoundException OutOfMemoryError) and the program runs properly without any error. Al thought the handling is not so relevant with the functionality of the code i chose them just to see when i can combine multiple exceptions in on handler :
import java.io.FileNotFoundException;
import java.lang.OutOfMemoryError;
public class exceptionTest {
public static void main(String[] args) throws Exception {
int help = 5;
try {
foo(help);
} catch (FileNotFoundException | OutOfMemoryError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean foo(int var) throws Exception {
if (var > 6)
throw new Exception("You variable bigger than 6");
else
return true;
}
}
But when i choose different type of exceptions the compiler gives me error . For example when i choose IOException and Exception i have the error the exception is already handled " :
import java.io.IOException;
import java.lang.Exception;
public class exceptionTest {
public static void main(String[] args) throws Exception {
int help = 5;
try {
foo(help);
} catch (IOException | Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static boolean foo(int var) throws Exception {
if (var > 6)
throw new Exception("You variable bigger than 6");
else
return true;
}
}
So why is this happening ? Why in one occasion i can use multiple exception in handler and in the other not ? Thank you in advance.
You are getting the message because IOException is a subclass of Exception. Therefore, if an IOException were thrown, it would be caught by a catch (Exception e) statement, so catching it as an IOException is redundant.
The first example works because neither FileNotFoundException nor OutOfMemoryError is a subclass the other.
However, you can catch sub-classed exceptions using the separate catch statement:
try{
// code that might throw IOException or another Exception
} catch (IOException e) {
// code here will execute if an IOException is thrown
} catch (Exception e) {
// code here will execute with an Exception that is not an IOException
}
If you do this, please note that the subclass must come first.

How to return value and Exception (if it is there.)

I have helper class in which I have written this function.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (TestLinkAPIException t) {
t.printStackTrace();
}
return createdProject;
}
now I am calling this function from GUI part where I have written
String createProject=//called above function.
now If error occur in above code I want to show error to the user.
my question is how I get back the created string and error message if some Exception occur
Create a Custom Exception
Add your String value as an instance field of that Custom Exception.
Throw the custom exception with the String values passed in.
Now you have the exception and the String as well.
If you have a Java 7, then you can use Multi-Catch exception block.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException | TestLinkAPIException e) {
e.printStackTrace();
throw new Exception("Error creating createdProject", e);
}
return createdProject;
}
If exception occurs, createdProject is never set.
You should throw the exception from this method and catch it in block where you calling this method.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject = doSomething();
} catch (Exception e) {
throw new Exception("Error creating Project");
}
return createdProject;
}
and where you calling this method you will have something like this.
try {
String str = createProject();
displayTheProjectCreated(str);
} catch (Exception e) {
// Oops something went wrong
displayErrorMessage(e);
}

Categories

Resources