You are on page 1of 11

Exception Handling

Errors
✦Syntax errors
– arise because the rules of the language have not been
followed
– detected by the compiler
✦Logic errors
–arise because the logic coded by the programmer was not
correct
–leads to wrong results and detected during testing
✦ Runtime errors or Exceptions
– Occur when the program is running and the environment
detects an operation that is impossible to carry out. 2
2
Runtime Error Example
public static void main(String[] args) {

int[] arr = new int[5];

for(int x = 0; x <= arr.length; x++ )


System.out.print(arr[x]);

} // throws ArrayIndexOutOfBoundsException
3

Runtime Error Example


public static void main(String[] args) {
Scanner s = new Scanner(System.in);

System.out.print(“Enter an integer: “);


int x = s.nextInt();

//rest of the code not shown here


} // may throw FormatException
4

4
Other Exceptions we have
encountered before
✦ NullPointerException
✦ ArithmeticException
– DivideByZeroException
✦ ClassCastExecption
✦ IOException
✦ FileNotFoundException
✦ EOFException

Exceptions are objects of Exception or Error class or their subclasses.

ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes


6

6
Unchecked Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

Checked Exceptions
ClassNotFoundException

IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException

LinkageError Several more classes

VirtualMachineError
Error
AWTError

Several more classes

8
Checked vs. Unchecked
✦ Java forces you to “handle” checked exceptions.

✦ You may or may not “handle” unchecked exceptions

“Handling” Checked Exceptions


✦Two possible ways

void p1() throws IOException { void p1() {


try {
riskyMethod(); riskyMethod();
}
} catch (IOException ex) {
...
}
}

(a) (b)

You can “handle” unchecked exceptions in the same fashion but it


is not required by the compiler. 10

10
Try-catch block
void p1() {
try {
//Statements that may throw exceptions
}

catch (ExceptionClass1 exVar1) {


Catch the
//code to handle exceptions of type Exception1; more
} specific
catch (ExceptionClass2 exVar2) { exceptions
// code to handle exceptions of type Exception2; before the
}
less
... specific
catch (ExceptionClassN exVarN) { ones
// code to handle exceptions of type exceptionN;
}
finally { // optional
// code executed whether there is an exception or not
}
// statement after try-catch-finally block
}
11

11

finally block
✦ Executed when try block is exited in any of
three ways:
– After last statement of try block
– After last statement of catch clause, if this catch
block caught an exception
– When an exception was thrown in try block and
not caught
✦ is executed even if there is a return
statement prior to reaching the finally block
12

12
Catching Exceptions
An exception is
thrown in
method3

main method { method1 { method2 {


... ... ...
try { try { try {
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
//Process ex1; //Process ex2; //Process ex3;
} } }
statement2; statement4; statement6;
} } }

• method3 may throw 4 types of exceptions: Exception1, Exception2,


Exception3, Exception4
• Exception1, Exception2, Exception3, Exception4 are not subclasses of
each other
• method3 does not have a try-catch block 13

13

Getting Information from Exceptions

✦ Some useful methods:


String toString() Returns a short description of the exception

void printStackTrace() Prints the stacktrace information on the console

✦ Example of printStackTrace() output


java.lang.NullPointerException at MyClass.mash(MyClass.java:9)
at MyClass.crunch(MyClass.java:6) at
MyClass.main(MyClass.java:3)
14

14
Example
public class Main {
public static void fun() {
PrintWriter output = null;
try {
output = new PrintWriter("text.txt");
output.println("Welcome to Java");
}
catch(IOException ex){
System.out.println(ex.toString());
ex.printStackTrace();
}
finally {
if(output != null) output.close();
}
}
}

15

15

Java 7 Improvements

✦ Catching Multiple Exceptions in single


catch block

catch (IOException | SQLException ex)


{
System.out.print(ex.toString());
}

16

16
Java Library Exceptions
✦ Many Java API methods throw exceptions.

✦ How do you know that the method you are going


to call may throw an exception?
– You can look up the class documentation to see if a
method throws exception

✦ Example:
See the Scanner class methods at:
https://docs.oracle.com/en/java/javase/13/docs/api/ja
va.base/java/util/Scanner.html#%3Cinit%3E(java.
io.File) 17

17

Throwing Exceptions
• create an object of appropriate Exception class
• throw it using the throw statement
• declare it in the method header in case of checked exception
• May or may not declare in case of unchecked exception

public void setRadius(double newRadius)


throws IllegalArgumentException
{
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}

18

18
Creating Custom Exception Classes

✦ Create custom exception classes if the predefined


classes are not sufficient.

✦ To declare custom exception class


✦ Create a class that extends Exception or a subclass of
Exception.
✦ Good practice: add
✦ An argument-less constructor
✦ Another constructor with one string type
parameter
19

19

public class InvalidRadiusException extends Exception {


public InvalidRadiusException(String s) {
super(s);
}
public InvalidRadiusException() { super(); }

public class Circle {


private double radius;
private static int numberOfObjects = 0;

public Circle() { this(1.0); }


public Circle(double newRadius) {
radius = newRadius; numberOfObjects++;
}

public void setRadius(double newRadius)


throws InvalidRadiusException {
if (newRadius >= 0) radius = newRadius;
else throw
new InvalidRadiusException(“Invalid Radius:” +
newRadius);
}
public static int getNumberOfObjects() {
return numberOfObjects;
} 20
}
20
public class Main {
public static void main(String[] args) {
try {
Circle c1 = new Circle(5);
c1.setRadius(-5);
Circle c2 = new Circle(20);
}
catch (InvalidRadiusException ex) {
System.out.println(ex.toString());
}

System.out.println("Number of objects created: " +


Circle.getNumberOfObjects());
}
}

Output:

Invalid radius: -5.0


Number of objects created: 1
21

21

When to create Custom


Exception classes
✦ Use the exception classes in the API whenever possible.

✦ You should write your own exception classes if you


answer ‘yes’ to one of the following:

– Do you need an exception type that isn't represented by those in the


Java platform?

– Do you want to pass more than just a string to the exception handler?

22

22

You might also like