Week 7 – Exceptions in JAVA

Exceptions in JAVA

What is an Exception?
  • Exception is an when abnormal condition occurs and stops the code from executing
  • An abnormal situation is something that should commonly not be occurring and is impossible for the system to deal with on its own, an example of an abnormal condition would be dividing a number by zero. We know it’s not possible and the program knows that too, therefore as soon as somebody tries executing that piece of code the entire code it crashed. Hence exceptions are specifically introduced to deal with these situations and prevent the codes from crashing. When an exception is raised either the code is stopped or interrupted, nor does the user continue making these mistakes since the exception inform them what they were doing wrong.
  • Exceptions occur during the run time and not the compile time.
  • The keywords for Exception are: try, catch, finally, throw, throws
What are they used for?
  • Exceptions are commonly used to overcome or recover from exceptional situations
  • Exceptions are raised to stop the code from cashing, to let it fully execute and to let users know what went wrong (by passing a message through the raised exception).
  • An example of a commonly raised exception is when a particular input is being expected but something else is being passed in
  • Exceptions tend to be a standardized way of dealing with errors also.
  • They give a good amount of information to the user to recover from that situation via their name and their message. For instance diving a number by zero should give the user an Arithmetic exception which gives the user a basic understanding of their mistake- and in this case it’s an arithmetic mistake he/she is making.
Exception Hierarchy

Object class –> Throwable class

Throwable class has two categories: ErrorException

Exception Class further breaks down into two categories: Runtime/Unchecked  & Checked Exceptions.

Exception Hierarchy

Error indicate irrecoverable conditions that occur during the program execution. However we won’t need to worry about them in this course. All we care about in B07 is Exceptions. Unlike errors, exceptions can be handled to prevent the program from terminating automatically.

The following methods are useful to study, as all the exception subclasses inherit functions from the “Throwable” class.

Constructors of Throwable: Throwable(), Throwable(String message)
Other useful methods: getMessage(), printStackTrace(), getStackTrace()

Throwable() method – Constructs a new throwable with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to initCause(java.lang.Throwable).

Throwable(String message)- Constructs a new throwable with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to initCause(java.lang.Throwable).

getMessage() – Returns the detail message string of this throwable


Runtime Exception (Unchecked Exception)

Runtime Exception is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. An example of a runtime exception would be: ArithmeticException, IndexOutOfBoundsException, NoSuchElementException, NullPointerException etc.

When these exceptions are raised the class does need to extend this super class, but the functions don’t need to “throw” an exception.

Here’s an example:

public class MyException extends RuntimeException{}

class Myclass {

public class(){}

public void m() /* NO throws */ {

if () {

throw new MyException(“oops”){}

}

}

What is important here to notice is that:

  1. First- The Exception class we create has to be extending either the the RunningtimeException(Unchecked Exception) or Exception (Checked Exception)
  2. Second – If we are expecting an exception, we normally write that beside the function saying something like “throws MyException” before opening the curly bracket. but we do not do that for the RunningtimeException subclasses
  3. Third- When you are expecting the code to crush under some certain condition, this is what you do- you define that condition under the if statement, if (count==0){ and under the if statement this is what you write- “throw new yourExceptionName(“your exception message”)”

Checked Exception (Exception)

Here’s an example of a Checked Exception:

public class MyException extends Exception{…}

public MyClass{

public void m() throws MyException{

if (){

throw new MyException(“oops!”){..}

}

}

}

Examples of Checked Exceptions are: IOException, NoSuchMethodException.


When to use what exception?

  • Use checked exceptions for conditions from which the caller can reasonable be expected to recover (for example no such method exception)
  • Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations (such as sending in an invalid index number or no such element exception- the programmer can check this before they call that method)
Main Code (try-catch statements)

How do I deal with exceptions in the main method? What you can use in your main method to overcome exceptions is the famous “try and catch” statement.

When you are calling a function that you know may throw an exception, instead of bluntly calling it, what you can do is try calling that function. So, what does this try do? as the word suggests, the try statement attempts to safely execute your code however if it faces any exceptions it stops trying and executing the code, instead it goes under the catch statement immediately that catches the exception raised.

Here’s an example:

try {

myVariable.myMethod(42, 2);

} catch (MyException e1) {

System.out.println(“No such node: ” + e1.getMessage());

}

Where myVariable is an instance variable, myMethod is the method applied on that instance variable that may throw an exception therefore it’s under the try statement. MyException is a new class of exception I’ve created that extends Exception (Checked Exception) e1 is the name of the instance of MyException class and under the catch statement, if an exception is raised, I print the message of my MyException class e1. I’ve inherited the message from the superclass of MyException class, this is what MyException class looks like:

public class NoSuchNodeException extends Exception {

public NoSuchNodeException(){

super();

}

public NoSuchNodeException(String message){

super(message);

}

}


The “finally” clause

  • Try and catch clause is much like the if and else clause, a try can have a series of catch clauses.
  • However after the last catch clause, you can have a “finally” clause
  • Finally does not resemble the last else of the if statement by any means
  • The finally clause is ALWAYS EXECUTED whether an exception was thrown or not, or whether or not the thrown exception was caught

Example: 

Suppose ExSup is the parent of ExSubA and ExSubB. – Anya’s example

try {

myVariable.myMethod(42, 2);

} catch (ExSubA e) {

// We do this if an ExSubA is thrown.

} catch (ExSup e) {

// We do this if any ExSup that’s not an ExSubA is thrown.

} catch (ExSubB e) {

// We never do this, even if an ExSubB is thrown.

} finally {

// We always do this, even if no exception is thrown.

}


Detailed Differences

Differentiate the RuntimeException() from Exception()

Consider the following code throwing RuntimeException (Unchecked Exception) is one case and Exception (Checked Exception) in the other case, the differences are also pointed out in the bullet points below:

public class DifferentiateExceptions{

 public static void throwit(){
    throw new RuntimeException();
 }
 
 public static void main(String args[]){
   try {
     System.out.println("Hello!");
     throwit();
     System.out.println("Done!");
   } finally {
     System.out.println("Finally!");
   }
 }
public class DifferentiateExceptions{

 public static void throwit() throws Exception{
    throw new Exception();
 }
 
 public static void main(String args[]) throws Exception{
   try {
     System.out.println("Hello!");
     throwit();
     System.out.println("Done!");
   } finally {
     System.out.println("Finally!");
   
 }

Consider the two examples of code one using RuntimeException and the other using Exception and try to notice and differences and derive a conclusion, then compare your conclusion my conclusions below:

Runtime Exception Conclusions:

  • The method that is creating and throwing a Runtime Exception does NOT need to declare “throws RuntimeException”
  • If under some code the function that might be throwing an exception is written with try and finally clause, then java executes the command of try statement until the runtime exception is encountered and the command under finally clause and only then crashes.
  • On the other hand if we have try and catch and finally statements, the try command is executed until the exception appears, if it exception is caught with the catch clause it safely proceeds and executes the command under the finally clause and does not crash at all, however if the catch statement fails to catch the exception, the code crashes after the code under finally clause is executed.
  • The try clause needs to have either a catch or a finally clause, it cannot exist on its own.
  • The class or method – main in our case- which calls the method throwing a runtime exception does not need to declare “throws Exception()”

Checked Exception Conclusions:

  • The method that is creating and throwing an Exception HAS TO DECLARE “throws Exception”
  • The function that calls the method which is creating and throwing an exceptions also HAS TO DECLARE “throws Exception”
  • If the line that might be causing the code to crash/raising an exception is written with try and finally clauses only, then Java executes the command of try statement until the exception is encountered and the command under finally clause and only then crashes.
  • On the other hand if we have try and catch and finally statements, the try command is executed until the exception appears, if it exception is caught with the catch clause it safely proceeds and executes the command under the finally clause and does not crash at all, however if the catch statement fails to catch the exception, the code crashes after the code under finally clause is executed.
  • The try clause needs to have either a catch or a finally clause, it cannot exist on its own.

 

 

Leave a comment