There is a method:

public String formatString(String str, int resId) { return String.format("%s %s", context.getResources().getString(resId), str); } 

How to make it check for him (using try / catch ) so that int resId does not equal 0, namely if it suddenly equaled 0, then the action would not be performed.

    3 answers 3

    If you need to check only for equality / inequality resId zero, then try-catch not needed and you can do with a simple if-else .

    If you want it with try-catch , then:

     public String formatString(String str, int resId) { String result = ""; try { result = String.format("%s %s", context.getResources().getString(resId), str); } catch(Resources.NotFoundException e) { // обработка исключения } return result; } 

    It handles the exception Resources.NotFoundException , which is generated when the resource with the given resId not found (in particular, if resId == 0 ).

    • sorry, but where does it figure that the value should not be zero? - Inkognito
    • @Inkognito, Updated the answer. - post_zeew
    • what you need the only thing that says that catch is empty. In the processing of an exception, there is a type of inscription that you entered 0 or something else? - Inkognito
    • @Inkognito, I do not know how your program should work in this situation. The behavior of the program in such cases is set by its developer and only by him. Third-party people will not be able to advise you of something specific in this situation. You can display a message that a line with such an identifier was not found, or you can do something else. - post_zeew

    Did you read the question yourself? Catch the condition? What?

    As far as I understand, you want to check if resId is not equal to zero. If you know what to do, in the case when it turns out to be zero, then the usual if:

     if (resId == 0) { ... } 

    If you do not know, generate an exception:

     if (resId == 0) { throw new IllegalArgumentAxception("resId = 0!") } 
    • corrected the question. I want that at resId == 0 action would not be fulfilled. + I don’t know how to connect it with my method. - Inkognito
    • Still not true. What does the action mean failed? If the type of the function were void, that is, it in fact simply makes an action, has a side effect in a more professional language, then it would be possible through verification. But here you have a function that returns a String, which means you have to decide what will be returned, in the case resId = 0. If you just output, it can be an empty string "" and some string "undefined". And if you do not know what to return, you can return null or throw an exception. But then in the external code you will need to think about handling such situations. - Uraty

    Isn't it easier to make a check when calling a method

     if (resId != 0){ formatString(myString, resId); }