\documentclass[10pt]{article}

\usepackage{hyperref}
\usepackage[a4paper, total={6in, 8in}, top=.75in, bottom=1in]{geometry}
\usepackage{graphicx}
\usepackage{comment}
\usepackage{url}
\usepackage{courier}
\usepackage{color}
\usepackage{amssymb}

\usepackage[normalem]{ulem}
\useunder{\uline}{\ul}{}
\DeclareGraphicsExtensions{.pdf,.png,.jpg}
\usepackage{color}
\newcommand*\ShiftLeft{\ll}
\newcommand*\ShiftRight{\gg}
\newcommand*\BitOr{\mathrel{|}}
\newenvironment{ppl}{\fontfamily{courier}\selectfont}{\par}


\definecolor{pblue}{rgb}{0.13,0.13,1}
\definecolor{pgreen}{rgb}{0,0.5,0}
\definecolor{pred}{rgb}{0.9,0,0}
\definecolor{pgrey}{rgb}{0.46,0.45,0.48}

\usepackage{listings}
\lstset{language=Java,
  showspaces=false,
  showtabs=false,
  breaklines=true,
  showstringspaces=false,
  breakatwhitespace=true,
  commentstyle=\color{pgreen},
  keywordstyle=\color{pblue},
  stringstyle=\color{pred},
  basicstyle=\ttfamily,
  moredelim=[il][\textcolor{pgrey}]{$$},
  moredelim=[is][\textcolor{pgrey}]{\%\%}{\%\%}
}

\setlength\parindent{0pt}
\begin{document}
\title{Building Blocks -- Exceptions, Chapter 4.6}
\author{Dr. Yvon Feaster}
\date{}
\maketitle

\section*{Exceptions}
So, what is an exception?  The term is short for {\em{exceptional event}}.  Exceptions are events that disrupt normal execution of a programs.  \\

When an exception occurs (an error) an exception object is created.  This object contains information about the error, the type of error, state of the program, and how to handle the exception.  This is called {\em{\textit{throwing an exception}}}.  When an exception is thrown the runtime system searches the call stack for a block of code to handle the exception.  The block of code is called an exception handler.  The search begins with the method in which the error occurred and proceeds through the call stack in the reverse order in which the methods were called.  If an exception handler is not found the program terminates.  \\

There are three kinds of exceptions

\begin{enumerate}
\item Checked exceptions  --  an exception that involves user error or a problem that cannot be foreseen by the programmer.  Ex.  file that could not be opened or does not exist --  These errors can not be ignored at compile time.
\item Runtime Exceptions -- an exception that most likely could have been avoided by the programmer -- they are ignored at compile time.  Usually caused by programming bugs such as logic errors or improper use of an API.  
\item Errors -- not really exceptions, but problems that occur outside of the perview of user or programmer  -- stack overflow is an example. Another example -- suppose a file is able to be opened but the data is not able to be read.   These errors are ignored at compile time.  
\end{enumerate}

\begin{figure}[h]
\begin{center}
  \leavevmode
  \includegraphics[width =0.60\textwidth]{Exception_Hierarchy.pdf}
\end{center}
\caption{Exception Hierarchy}
\label{fig:exception_hierarchy}
\end{figure}

Figure~\ref{fig:exception_hierarchy} depicts the basic exception hierarchy.  All exception classes are subtypes of the java.lang.Exception class.  The exception class is a subclass of the Throwable class.  Other than the exception class there is another subclass called Error which is derived from the Throwable class.  \\

The Exception class has two main subclasses:  IOException class and RuntimeException Class. \footnote{The above section came from \url{http://www.tutorialspoint.com/java/java_exceptions.htm}}  \\

Catching Exceptions:\\

A method catches an exception using a combination of the try and catch keywords.  To generate an exception, the try/catch keywords form a block around the code.  While in the protected block of code, if an exception occurred the catch block that follows the try is checked.  The exception is passed to the catch block much as an argument is passed into a method parameter.  An example is shown below. 

\begin{lstlisting}
//The following code throws an array out of bounds exception.
//File Name:  ExcepTest.java

import java.io.*;
public class ExcepTest
{
   public static void main(String [] args)
   {
      try
      {
         int a[] = new int[2];
         System.out.println("Access element three :" + a[a]);
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Exception thrown :" + e);
      }
      System.out.println("Oout of the block");
   }
}

This code produces the following:

Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3
Out of the block

You can also have multiple catch blocks such as the following:

try
{
   //protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}

//The above statements show that you can have multiple catch statements following one try.  If an exception occurs each catch statement would be checked before moving to the next until the exception either is caught or falls through all catches.  
\end{lstlisting}

Another keyword used with exception handling is finally.  It is used to create a block of code that is always executed whether or not an exception has occurred.  This allows you to run any cleanup-type statements that you want to execute.  It also appears at the end of the catch block, as follows:

\begin{lstlisting}

try
{
   //protected code
}catch(ExceptionType1 e1)
{
   //Catch block
}catch(ExceptionType2 e2)
{
   //Catch block
}catch(ExceptionType3 e3)
{
   //Catch block
}finally
{
   // This block of code always executes
}

\end{lstlisting}

Declaring your own exception.  A couple things to keep in mind with developing your own exception is as follows:

\begin{enumerate}
   \item All exceptions must be a child of Throwable (refer back the Figure~\ref{fig:exception_hierarchy})
   \item If you are writing a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class.
   \item If you are writing a runtime exception, you must extend the RuntimeException class.  
\end{enumerate}

The following is an example of declaring your own exception.
\begin{lstlisting}

// File Name InsufficientFundsException.java
import java.io.*;

public class InsufficientFundsException extends Exception
{
   private double amount;
   public InsufficientFundsException(double amount)
   {
      this.amount = amount;
   } 
   public double getAmount()
   {
      return amount;
   }
}

//This demonstrates the use of the user-defined exception.

// File Name CheckingAccount.java
import java.io.*;

public class CheckingAccount
{
   private double balance;
   private int number;
   public CheckingAccount(int number)
   {
      this.number = number;
   }
   public void deposit(double amount)
   {
      balance += amount;
   }
   public void withdraw(double amount) throws
                              InsufficientFundsException
   {
      if(amount <= balance)
      {
         balance -= amount;
      }
      else
      {
         double needs = amount - balance;
         throw new InsufficientFundsException(needs);
      }
   }
   public double getBalance()
   {
      return balance;
   }
   public int getNumber()
   {
      return number;
   }
}


//This program invokes the deposit and withdrawal methods of Checking Acount

// File Name BankDemo.java
public class BankDemo
{
   public static void main(String [] args)
   {
      CheckingAccount c = new CheckingAccount(101);
      System.out.println("Depositing $500...");
      c.deposit(500.00);
      try
      {
         System.out.println("\nWithdrawing $100...");
         c.withdraw(100.00);
         System.out.println("\nWithdrawing $600...");
         c.withdraw(600.00);
      }catch(InsufficientFundsException e)
      {
         System.out.println("Sorry, but you are short $"
                                  + e.getAmount());
         e.printStackTrace();
      }
    }
}

This code produces the following results:
Depositing $500...

Withdrawing $100...

Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
        at CheckingAccount.withdraw(CheckingAccount.java:25)
        at BankDemo.main(BankDemo.java:13)

\end{lstlisting}

A great deal of this document came from \url{http://www.tutorialspoint.com/java/java_exceptions.htm} and from The Java Tutorial (online and or the book).  
\end{document}


