Android unreported exception IOException error - java

I am new to android apps development. Recently,Im writing an application which able to show public ip based on Ipify. So far, i already:
Download the required jar file and put inside libs folder
I also compile file within gradle
Then i import required class it to my class
How to use Ipify, according to its website:
import org.ipify.Ipify;
public class HelloIP {
public static void main(String[] args) throws IOException {
System.out.println(Ipify.getPublicIp());
}
}
I write the following method to be invoked from another class:
public static String getPublicIp() throws IOException{
String ip = Ipify.getPublicIp();
return ip;
}
Another Class
//Get wifi
getWifiName wifiInfo = new getWifiName();
String myIP = wifiInfo.getPublicIp();
However, i keep getting:
Error:(52, 43) error: unreported exception IOException; must be caught
or declared to be thrown
I tried to modify the code and use the following try and catch, but still got the same error.
public static String getPublicIp() throws IOException{
String myip = Ipify.getPublicIp();
try{
return myip;
}
catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
}
Im not too good in catch and throw exception, and already spent the whole day for this.I dont have idea anymore to fix this error..T.T

public static String getPublicIp() {
try{
return Ipify.getPublicIp();
}catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
return null;
}
In case it didn't help, clean project in your IDE. You may have some data cached and it might be a reason.
Your problem is in another class! As you have declared the method getPublicIp() to throw IOException that class is afraid of receiving the Exception and therefor requests catching it.
In Java you have two types of Exceptions. Checked and unchecked. Checked Exceptions must be caught.
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.
Unchecked Exceptions are those which extend RunTimeException. They are used for marking unexpected states usually caused by user's input. They shouldn't cause harm and should be worked out with business logic. You don't have to catch them, but sometimes you should.
On the other hand there are Checked Exceptions which mark dangerous situations. For example the application being unable to open a file. As those situations are found dangerous, you must catch them.
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
or using the fact, that they all extend Exception:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
or since Java 7:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};

Related

Activiti`s RuntimeServiceImpl::startProcessInstanceByKey cannot work well in a concurrent environment

I've got a very strange question in RuntimeServiceImpl::startProcessInstanceByKey.
The code is like this:
#Override
public String startProcessInstanceByKey(String processDefinitionKey, String businessKey,
String authenticatedUserId, Map < String, Object > variables) throws RiskManageException {
log.info("startProcessInstanceByKey,收到开启工作流 processDefinitionKey:{} ,businessKey:{},authenticatedUserId:{},variables:{}", //This can be printed normally
processDefinitionKey, businessKey, authenticatedUserId, JSON.toJSON(variables));
try {
Assert.notNull(authenticatedUserId, "userCode 不能为空");
Assert.notNull(processDefinitionKey, "流程定义key 不能为空");
processCoreService.getIdentityService().setAuthenticatedUserId(authenticatedUserId);
return processCoreService.getRuntimeService()
.startProcessInstanceByKey(processDefinitionKey, businessKey, variables).getProcessInstanceId(); //This statement didn`t execute
} catch (Exception e) {
throw new RiskManageException(ExceptionCodeEnum.START_PROCESS_ERROR, e); //Here throws an exception but the caller didn`t catch any
}
}
The process instance couldn't be created sometimes in a concurrent environment without any exception. It often happens when JDBC connections are about to use up. I want to know more detailed information, what should I do?

Testing if custom exception was thrown when a run time exception is thrown using mockito

I have this code where I'm catching some exception and throwing a custom exception instead.
#Override
public void config() throws CustomException{
File jsonFile = new File("config.json");
try {
ConfigMapper config = mapper.readValue(jsonFile, ConfigMapper.class);
try {
this.instanceId = Integer.parseInt(config.getConfig().getClientId());
this.configParams = config.getConfig().getConfigParams();
} catch (NumberFormatException ex) {
throw new CustomException("Please provide a valid integer for instance ID", ex);
//LOGGER.log(Level.SEVERE, "error initializing instanceId. Should be an integer " + e);
}
} catch (IOException ex) {
throw new CustomException("Error trying to read/write", ex);
// LOGGER.log(Level.SEVERE, "IOException while processing the received init config params", e);
}
}
I need to write a unit test for this and below is how I wrote it.
#Test
public void should_throw_exception_when_invalid_integer_is_given_for_instanceID(){
boolean isExceptionThrown = false;
try{
Mockito.doThrow(new NumberFormatException()).when(objectMock).config();
barcodeScannerServiceMock.config();
} catch (CustomException ex) {
isExceptionThrown = true;
}
assertTrue(isExceptionThrown);
}
But its throwing a number format exception and not the CustomException as I want it to be. But this makes sense as I'm using the mock object to throw the exception as a result of which my code logic is not executed. But if that's the case, how do I test this scenario? Please advice.
1.) Remove the line Mockito.doThrow(new NumberFormatException()).when(objectMock).config();
2.) Change the Client-ID in your JSON-File to something that cannot be converted to an Integer.
this.instanceId = Integer.parseInt(config.getConfig().getClientId()); will fail due to that and thus throw an exception.
One advice regarding names: The name of your test method should be what's written in the Java-Doc. Just name it "testCustomException" & explain the methods function in the Java-Documentation. There are Naming-Conventions in Java (click here) which are basically general guidelines.
Practicing these is very helpful as it allows you to quickly get into your code again after not working on it for a month or so due to the increased readability.

Correct way to handle method exception? [duplicate]

This question already has answers here:
Catching an Exception from a called Method
(4 answers)
Closed 7 years ago.
i seem to be a bit confused on how to throw exceptions and when it would be used to create your own exceptions.
i have this code and was wondering if i went about this the correct way
heres the method:
public void setHireYear(int year) throws Exception {
try{
if (year <= CURRENT_YEAR && year >= CURRENT_YEAR - MAX_YEARS_WORKED) {
hireYear = year;
}
else{
throw new HireYearException(year);
}
}catch(HireYearException e){
e.toString();
}
}
and heres the exception class:
public class HireYearException extends Exception
{
private int hireYear;
/**
* Constructor for objects of class HireYearException
*/
public HireYearException(int hireYear)
{
this.hireYear = hireYear;
}
public String toString()
{
return "Hire year cannot exceed Current year, your hire year is - " + hireYear;
}
}
why would throwing a custom exception be better than throwing pre defined exceptions?
Specific customs exceptions allow you to segregate different error types for your catch statements. The common construct for exception handling is this:
try
{}
catch (Exception ex)
{}
This catches all exceptions regardless of type. However, if you have custom exceptions, you can have separate handlers for each type:
try
{}
catch (CustomException1 ex1)
{
//handle CustomException1 type errors here
}
catch (CustomException2 ex2)
{
//handle CustomException2 type errors here
}
catch (Exception ex)
{
//handle all other types of exceptions here
}
Hence it provides you (benefits and why to create it)
1.specific exceptions allow you a finer level of control over your exception handling
2.Provides a type safe mechanism for a developer to detect an error condition.
3.Add situation specific data to an exception
Ideally this data would help another developer track down the source of the error.
4.No existing exception adequately described my problem
Source

Using specific try catch, error overrides

This is my Exception:
public class MyException extends Exception {
private String errorCode="Unknown_Exception";
public MyException(String message, String errorCode){
super(message);
this.errorCode=errorCode;
}
public String getErrorCode(){
return this.errorCode;
}
}
Now immagine the next scenario, the code is way too long to paste here:
1 I got a Presentation class made in Swing in Presentation package
2 In package calculations I made simple operations with few numbers from received database fields
3 In package connections I got the database connections
Trouble comes here:
-In presentation layer I catch all errors, like this:
try {
//here is a method called updateCombo() wich throws:
//throw new MyException(e.getMessage(),"ERROR_UPDATING_COMBO_BOX");
} catch (MyException ex) {
try {
//Here we process error code, if error is not defined, uses default errors.
processCode(ex);
} catch (MyException ex1) {
Logger.getLogger(Presentacion.class.getName()).log(Level.SEVERE, null, ex1);
}
}
processCode is a simple list with cases, like this:
private void processCode(MyException e) throws MyException {
switch (e.getErrorCode()) {
case "ERROR_UPDATING_COMBO_BOX":
lblErrorText.setText("Error updating combo.");
throw e;
case "ERROR_SELECTING_PRIMARY_KEY":
lblErrorText.setText("Error selecting PK");
throw e;
case "ERROR_OPENING_CONNECTION":
lblErrorText.setText("Error opening connection.");
throw e;
default:
lblErrorText.setText("Excepcion not defined: "+ e.getMessage());
e.printStackTrace();
}
This is the scenario, the connection fails in 3rd package and leads to this:
throw new MyException(e.getMessage(),"ERROR_OPENING_CONNECTION");
As I said, the error is thrown to the upper layer with throws clause in method header, this beeing 2nd package.
2nd package also throws a new exception to Presentation, because of failing connection:
throw new MyException(e.getMessage(),"ERROR_SELECTING_PRIMARY_KEY");
Presentation methods also throw this exception becase 2nd layer failed:
throw new MyException(e.getMessage(),"ERROR_UPDATING_COMBO_BOX");
The main problem:
Using debug i found out that the program does what it has to do. It gets to the connection layer and does this successfully:
throw new MyException(e.getMessage(),"ERROR_OPENING_CONNECTION");
But, in 2nd layer, calculations, if connection fails it throws a new exception:
throw new MyException(e.getMessage(),"ERROR_SELECTING_PRIMARY_KEY");
This is the problem:
throw new
throwing new exception overrides ERROR_OPENING_CONNECTION with ERROR_SELECTING_PRIMARY_KEY. When it gets to presentation due to its "throw new" overrides ERROR_SELECTING_PRIMARY_KEY with ERROR_UPDATING_COMBO_BOX, resulting in the final error shown in the screen:
lblErrorText.setText("Error updating combo.");
Is there any way to return to presentation once first error is caught without overriding by next errors?
Maybe I misunderstood the concept but I want to catch all possible errors because:
-If connection is OK but method in 2nd layer fails it should throw ERROR_SELECTING_PRIMARY_KEY.
-If 2nd layer (calculations) does it OK but there is error in presentation it should lead to ERROR_UPDATING_COMBO_BOX.
You can use e.getCause() which will return a Throwable and check if this cause belongs to MyException. In case it is, you can check the e.getCause() again recursively until you obtain the deepest error code in the stacktrace and perform the validation for this exception.
Here's an example:
public MyException getDeepestException(MyException e) {
Throwable t = e.getCause();
if (t instanceof MyException) {
return getDeepestException((MyException)t);
}
return e;
}
As pointed out by #RealSkeptic, in order to use this approach, you will need to add an additional constructor to your custom exception:
public MyException(String message, Throwable cause, String errorCode){
super(message, cause);
this.errorCode = errorCode;
}
And when throwing your exception, call the proper constructor:
try {
//...
} catch (SomeException e) {
throw new MyException(<a proper message should be here>, e, "ERROR_SELECTING_PRIMARY_KEY");
}
If I understand you correctly, if the exception caught by one package happens to be a MyException, you want the original MyException to be passed up, otherwise (if the exception is some other type of Exception) you want to create a new MyException.
In this case, you should have two catch clauses.
try {
// Whatever you do in the try clause
} catch ( MyException myEx ) {
throw myEx;
} catch ( Exception e ) {
throw new MyException(e.getMessage(),"ERROR_SELECTING_PRIMARY_KEY");
}

Generic Exception Handling

I found below code for exception handling which handles all execptions of thrown by application including runtimes.
public static void handleException(String strMethodName,
Exception ex) throws CustomException{
String strMessage = "";
try {
throw ex;
}
catch (NullPointerException npe){
logger.log(pr, strMethodName, npe.getMessage());
strMessage=ERR_02;
throw new CustomException(strMessage);
}
catch(IndexOutOfBoundsException iobe) {
logger.logMethodException(strMethodName,iobe.getMessage());
strMessage=ERR_03;
throw new CustomException(strMessage);
}
... So On
}
Below are some of the disadvantages that I think:
To idenitify root cause of the exception we will need to always check for the Message string.
No sepearation of type of exceptions
Advantage:
Less code. (Code can be minimized)
Can you please let me know whether I should go with such mechanism or not.
Not sure of the circumstances which you are using the code.
In your approach, you are not rethrowing the exception object which may be used for debugging
public static void handleException(String strMethodName,
Throwable th){
String strMessage = "";
try {
throw th;
}
catch (Throwable thr){
logger.log(pr, strMethodName, npe.getMessage());
//get the appropriate error code from a method
strMessage=getErrorCode();
throw new CustomException(strMessage, th);
//CustomException is of type RuntimeException
}
}
By catching and "THROWING" the Throwable object you are sure that even errors are handled properly. [It is important not to suppress the Throwable object]

Categories

Resources