Skip to content

Exceptions and Assertions

Russell Saerang edited this page Nov 24, 2021 · 3 revisions

Error Handling

We can exceptions to track reasons for failure of the program.

Types of Exceptions

There are two types of exceptions:

  • Checked exceptions: Checked exceptions are checked at compile-time. if a method is throwing a checked exception then it should handle the exception using try-catch block or it should declare the exception using throws keyword, otherwise the program will give a compilation error. (Source)
  • Unchecked exceptions: Exceptions that are checked at runtime (Some examples of unchecked exceptions are NullPointerException, IllegalArgumentException, and SecurityException)
  • ArithmeticException is a unchecked exception. For instance, the class 'Example' shown below compiles, but the exception is thrown when it is run.
//source: https://beginnersbook.com/2013/04/java-checked-unchecked-exceptions-with-examples/

class Example {  
   public static void main(String args[])
   {
	int num1=10;
	int num2=0;
	int res=num1/num2; //throws ArithmeticException due to division by 0
	System.out.println(res);
   }
}

Exception Handling

Throwing an exception

One way to handle an exception is to throw it. In the example below, using the throwing of exceptions, we can pinpoint what went wrong in the inputs such as if the argument was null.

static <K> Logger<K> of(K newValue) {
        K value = Optional.ofNullable(newValue).orElseThrow(() -> new IllegalArgumentException("argument cannot be null"));
        if (newValue instanceof Logger ) {
            throw new IllegalArgumentException("already a Logger");
        }
        return new Logger<K>(newValue);
    }

Try-Catch Blocks

Another way to handle is using try and catch blocks.

//source: https://www.baeldung.com/java-exceptions

public int getPlayerScore(String playerFile) {
    try (Scanner contents = new Scanner(new File(playerFile)) ) {
        return Integer.parseInt(contents.nextLine());
    } catch (FileNotFoundException e) {
        logger.warn("Player file not found!", e);
        return 0;
    } catch (IOException e) {
        logger.warn("Player file wouldn't load!", e);
        return 0;
    } catch (NumberFormatException e) {
        logger.warn("Player file was corrupted!", e);
        return 0;
    } finally { //code that will be executed regardless whether an exception occurs}
}

//Take note that another possible syntax is catch (IOException | NumberFormatException e) where | can be understood like "or"

When writing multiple catch blocks, it is important to order the exceptions being caught in terms of specificity. For instance, FileNotFoundException extends IOException so it should be positioned higher. If we put the most general exception first, we might not be able to catch other exceptions that can reveal the specifics of what went wrong since these exceptions were all technically caught as well.

Another example: NoSuchElementException has a subclass InputMismatchException so if you catch a NoSuchElementException you also catch InputMismatchException. Thus, we position InputMismatchException higher in the try-catch block.

Custom Exceptions

It is also possible to create your own exceptions by creating a class that extends from an exception

//source: https://www.baeldung.com/java-exceptions

public class IncorrectFileNameException extends Exception { 
    public IncorrectFileNameException(String errorMessage) {
        super(errorMessage);
    }
}

//source: lecture notes
class IllegalCircleException extends IllegalArgumentException {
        IllegalCircleException(String message) {
            super(message);
        }

        @Override
        public String toString() {
            returnIllegalCircleException: “+getMessage():
        }
}   

Assertions

Assertions can be used to check if our assumptions during coding are correct. We can check before and after method invocation depending of the purpose of the assertion.

Take note that to check for assertions when running code : you need to use java -ea Main / jshell - R -ea

//source: https://www.geeksforgeeks.org/assertions-in-java/
     if ((x & 1) == 1)  
         {  }
         else // x must be even 
         { assert (x % 2 == 0); }
Clone this wiki locally