Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage
This lecture Summary on polymorphism, multiple inheritance and interfaces Using Java exceptions The clauses throw, try, catch, finally in exception handling Creating your own exceptions Multiple exceptions
What can go wrong in a Java program while running? accessing an object through a null reference. attempting to access an array element through an index that is too large or too small. dividing by zero overflow e.g., exceeding the largest integer that can be represented in Java. retrieving an element from an empty database. etc.
Exception Handling - Why? Think about what can go wrong and deal with it appropriately! Handling these errors is carried out using Exception Handling. Exception handling allows programmers to write clear, more robust, and more fault-tolerant programs. Commercial products usually have more exception handling code than casual software.
Java Exception Handling Java Exception handling follows the following mechanism: Potential errors are dealt with in the vicinity of the code but the code may be polluted with the error processing. A Java programmer can use already defined kinds of exceptions but also define its own exceptions for the problem at hand.
Java Predifined Exceptions In Java, exceptions are classes derived from the class Throwable, which is also extended by Exception. The subclass RuntimeException concerns exceptions that can be thrown during the normal operation of the JVM. The subclass IOException concerns input/output data This forms a kind of hierarchy between the Exception classes. For example, IOException and RuntimeException are 2 sublasses of Exception. See the Java API for more details on the class hierarchy.
How do we define our own exceptions? public class NotNumberException extends Exception { String error; // state variable error message public NotNumberException () { //constructor 1 error = "This is not a valid number"; public NotNumberException ( String s) { //constructor 2 error = s; public String getmessage() { //get method return error;
Throwing Exceptions Exceptions can be thrown within a method function by using the keyword throws. public int intdivision(int num, int denom) throws NotNumberException { if (denom==0) { throw new NotNumberException("Cannot divide by 0"); return num/denom;
Catching Exceptions Exceptions can be caught by using the try-catch construct. public void callintdivision(int a, int b){ try { int res = intdivision(a, b); System.out.println(res); catch (NotNumberException e) { //return the corresponding error message System.out.println(e.getMessage());
Quick Quiz 1 What is the output after the execution of the following code? public int intdivision(int num, int denom) throws NotNumberException { if (denom==0) { throw new NotNumberException("Cannot divide by 0"); return num/denom; try { int res = intdivision(3, 0); System.out.println("result is "+res); catch (NotNumberException e) { System.out.println(e.getMessage()); 1. result is 3 2. Cannot divide by 0 3. result is 0 4. Not a number
Mutliple Catch Blocks public void readinputdata(){ FileReader file = null; try { file = new FileReader("data.txt");//reading from a fil char c = (char) file.read();//reads a char from file catch (FileNotFoundException ex) { // return appropriate error message catch (IOException e) { //return the corresponding error message System.out.println(e.getMessage()); FileNothFoundException is a Java pre-defined class, which deals with file handling e.g., opening or closing a file.
The Finally Block The finally block may be used to release any permanent resources the method might have allocated e.g., closing an open file. public void readinputdata(){ FileReader file = null; try { //code that throws an IOException and FileNotFoundException catch (FileNotFoundException e) { System.out.println(e.getMessage()); catch (IOException ex) { System.out.println(ex.getMessage()); finally { if (file!= null){ try { file.close(); catch (IOException e) { //deals with the exception
Quick Quiz 2 Consider the following code fragment. try { System.out.println("try block"); finally { System.out.println("finally block"); Which of the followings is correct? 1. The given code is illegal. 2. The given code will always throw a runtime error. 3. The given code is syntactically correct. 4. The given code trows an Exception error.
The Stack data structure A stack is commonly used data structure e.g., a pile of plates. It is known as a LIFO (Last-in-First-out) data structure. The insertion operation is known as push The removal operation is called as pop
Stack Operations push() store an element on the stack pop() remove an element from the stack top() get the top element of the stack without removing it isfull() check if stack is full isempty() check if stack is empty
Exercise Write a java code to handle a stack of integers: Use exception handling to write a method that pops an element from a Stack and that deals with the case wherein the stack is empty. Use exception handling to write a method that pushes an element into a stack and that deals with the case wherein the stack is full.
Model answers (1) Quiz 1-2 Quiz 2-3 Java code for the exercise
Model answers (2) public class IntegerStack { private int top; int size; int[] stack; public IntegerStack() { size = 10; stack = new int[10]; top = -1; public IntegerStack(int s) { size = s; stack = new int[size]; top = -1; public int pop() throws StackException { if (isempty()){ throw new StackException("Empty! cannot pop"); int i = stack[top]; top = top-1; return i; public void push(int i) throws StackException { if (isfull()) { throw new StackException("Full!Cannot push "+i); top = top+1; stack[top] = i; public boolean isempty() { return top==-1; public boolean isfull() { return top==size-1;
Model answers (3) public class StackException extends Exception { String error; public StackException () { super(); public StackException (String err) { error = err; public String getmessage() { return error;