开发者

Why i am getting Error if i use try catch

开发者 https://www.devze.com 2023-02-21 14:16 出处:网络
i wrote an function like public static boolean check()throws Exception { if(a==\"asd\") return true; else

i wrote an function like

public static boolean check()throws Exception
{
  if(a=="asd")
return true;
else
return false;
开发者_运维知识库
}

this works fine but if i use

public static boolean check()
{
try
{
  if(a=="asd")
return true;
else
return false;
}
catch(Exception e)
{
}
} 

it says you need to return an value,,,, is there is any difference between these two???


you need to return something in the catch, a method always need to return something, even in catch, unless you throw/rethow an exception.


Yes, there is a difference. Your second code block will catch any exception from the if statement and swallow it, and then resume running after the catch block. But there is no return statement there, so if there is any exception, the function will have no return value.

The first code block, on the other hand, uses throws to indicate that Exception descendants may escape from it instead of being caught, so it doesn't need to catch and handle anything itself, and the compiler is prepared to allow the function to not return anything (due to exiting early from an exception).


Java has methods, not functions. So you didn't write a function, but a method. Also, comparing strings with == does not work in Java. You have to call the equals() method instead:

if (a.equals("asd"))

The problem in your second piece of code is this: What happens if an exception occurs? The content of the catch block is executed, and after that the rest of the method is executed. Note that there is no code after the catch block. But the method requires that you return a boolean - you're missing a return statement. Change it like this:

public static boolean check()
{
    try
    {
        if (a.equals("asd"))
            return true;
        else
            return false;
    }
    catch(Exception e)
    {
    }

    // You need to add a return statement here
    return false;
}

There are some more comments that can be made about your code.

First of all, it's always a bad idea to leave a catch block empty. Because when an exception is caught, nothing will happen, and you'll never know that something went wrong. Always handle exceptions appropriately.

Also, code like this:

if (a.equals("asd"))
    return true;
else
    return false;

can be simplified like this:

return a.equals("asd");

The result of the expression a.equals("asd") is already a boolean; why would you check again if it's true or false and then return true or false?


Not all paths in the code will return a value. Since you have a catch there, if an exception is thrown, no value will be returned because the code in the catch will execute.


I think you should return the value at the end of function after catch. Try to store result in one boolean variable and return that variable after catch. This may solve your problem


A premise: a=="asd" is not 'wrong' but probably it is better to use a.equals("asd") because == compares pointers, not equality. For example ("asd"=="asd") == false but ("asd".equals("asd")) == false

If if(a=="asd") throws an exception, the flow goes in the catch, and then it exits without ever finding the return statement. the correct code could have a return statement inside the catch block


Jesper's answer pretty much covers it. I needed to show some code so therefore this separate answer.

You will have to decide in each situation how to handle exceptions. Jesper and LordSAK both chose to return 'false'. A problem with this is that you can't distinguish the error condition from the case that 'a' is not equal to "asd".

A possible solution is to change the method's return type to Boolean (the Object version of the primitive boolean) and return 'null' in case of an exception

public static Boolean check() {
    try {
        return "asd".equals(a);
    }
    catch(Exception e) {
        return null;
    }    
}

Another option is to re-throw your exception as an unchecked exception:

public static boolean check() {
    try {
        return "asd".equals(a);
    }
    catch(Exception e) {
        throw new RuntimeException("Problem during check", e);
    }    
}

A drawback of this approach is that the code calling your check() method does not expect a runtime exception to be thrown. Because this type of exception is unchecked the developer will not get a compiler warning if he doesn't surround the call to check() with try-catch.

A third option is to just declare the exception and let your calling code handle it. A full example:

import org.apache.log4j.Logger;

public class Checker {

    private static final Logger LOG = Logger.getLogger(Checker.class);
    private String a;

    public Checker(String value) {
        a = value;            
    }

    public boolean check() throws Exception {
        return "asd".equals(a);    
    }

    public static void main(String[] args) {
        Checker app = new Checker("Stackoverflow");     
        try {
            app.check();
        }
        catch(Exception e) {
            LOG.error("Problem during check", e);
        }                   
    }
}

An advantage is that you don't have to decide which value check() returns in case of an error, but instead you just return the error itself. This is actually the whole idea of 'throwing' exceptions.

As a rule of thumb: if you can't handle an exception within the method itself, then throw it and let the calling code deal with it.

An example from the wild: A method handling an exception itself.

private static final long DEFAULT_TIMEOUT = 60000;

public long getTimeout(String timeoutArg) {
    try {
        return Long.parseLong(timeoutArg);
    }
    catch(NumberFormatException e) {
        return DEFAULT_TIMEOUT;
    }
}

NB: I didn't compile or run any of this code, so there might be typos.

0

精彩评论

暂无评论...
验证码 换一张
取 消