Exception handling within if statements in Java

47,808

Solution 1

You should think of try/catch as any other statement. So you can put it inside any of two branches of if/then/else statement, but it have to be whole inside:

if(statement){
    ...    
    try{
        ...
    }catch(...){
    ...
    }
    ...
}else{
    ...    
    try{
        ...
    }catch(...){
    ...
    }
    ...
}

If you have to catch multiple exceptions you can achieve this by multiple catch parts:

    try{
        ...
    }catch(Exception1 e1){
    ...
    }catch(Exception2 e2){
    ...
    }catch(Exception3 e3){
    ...
    }

Solution 2

What you want here is to create your own Exception class.

To create an exception class say you need to extend Exception class. Here's an example. Lets say my custom exception class should be named as MyFileErrorException

So I create a new class like this -

class MyFileErrorException extends Exception {

    private String message = null;

    public MyFileErrorException() {
        super();
    }

    public MyFileErrorException(String message) {
        super(message);
        this.message = message;
    }

    public MyFileErrorException(Throwable cause) {
        super(cause);
    }

    @Override
    public String toString() {
        return message;
    }

    @Override
    public String getMessage() {
        return message;
    }
}

Now I need to throw this exception at will. So in Your case you wantto catch File delete exception so the code will like this -

if(file.delete()) 
      {
      System.out.println(file.getName() + " is deleted!");
      } else {
      try{
            System.out.println("Existing file cannot be deleted.")
            throw new MyFileErrorException("File Could not be deleted val is null");
      }catch(MyFileErrorException ex){

        //Do wahtever you want to do
      }

      } 
Share:
47,808
dwwilson66
Author by

dwwilson66

Visual Communications Professional with a background in technology. In the thick of learning Java, PHP & MySQL to augment my web skills. I'm taking a shine to programming a lot more than I thought I would.

Updated on January 01, 2020

Comments

  • dwwilson66
    dwwilson66 over 4 years

    I'm a relative newbie to custom error handling in Java, and I'm trying to figure out how to use catch statements to deliver specific messages inside of an if statement. I wanted to get some extra sets of eyes to look at what I'm trying to do and offer feedback before I completely overthink this and overdo it too badly.

    Consider: We have a directory of hourly log files and I have an on-demand reporting job creates a concatenation of all today's log files created so far. I want to add a step that checks for the existence of a concatenated log file, deletes it then creates it if present, or just creates it if it's not present. With the code below, I'm returning an exception if, for some reason, the new file cannot be created.

    try {
       File file = new File (destinationPath + "todayToNowLogFile.csv");
       if(file.exists())
       {
          if(file.delete()) 
          {
          System.out.println(file.getName() + " is deleted!");
          } else {
          System.out.println("Existing file cannot be deleted.")
          } 
       } else {
          System.out.println("File will be created.");
       }
    }
     //
    catch(Exception e) {
       System.err.println("Exception: ");
       System.out.println("Exception: "+ e.getMessage().getClass().getName());
       e.printStackTrace();
    }
    

    Now, in the case where the file cannot be deleted, I would like to display the exception preventing file deletion. First, I would need to catch that error, but then where do I put the try?

    Doing something like this...

    try 
    {  
       if(file.delete()) 
       {
          System.out.println(file.getName() + " is deleted!");
       }
    }
    else {
       catch(Exception eDel) {
           System.err.println("Exception: ");
           System.out.println("Exception: "+ eDel.getMessage().getClass().getName());
           eDel.printStackTrace(); 
        }
    }
    

    ....interrupts the if...then block. I'm not sure how to insert a try...catch within an if...then. Is there a way to do this? Or does my original code catch EVERY error associated with ANY operation on the file defined in the try block, and I would need to put if...then logic in the catch block, something along the lines of this pseudocode....

    catch(Exception e) {
       if(exception relates to file deletion) {
           "File delete exception " + exceptionMessages;
       } else if(exception relates to file creation) {
           "File create exception " + exceptionMessages;
       } else if(other exception) {
           "other exception " + exceptionMessage;
       } else {
           "no exceptions encountered"
       }
    }
    

    What's the most appropriate way to handle this type of situation?