Professional Documents
Culture Documents
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) {
} // throws ArrayIndexOutOfBoundsException
3
4
Other Exceptions we have
encountered before
✦ NullPointerException
✦ ArithmeticException
– DivideByZeroException
✦ ClassCastExecption
✦ IOException
✦ FileNotFoundException
✦ EOFException
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
6
Unchecked Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
Checked Exceptions
ClassNotFoundException
IOException
ArithmeticException
Exception AWTException
NullPointerException
RuntimeException
IndexOutOfBoundsException
Object Throwable Several more classes
IllegalArgumentException
VirtualMachineError
Error
AWTError
8
Checked vs. Unchecked
✦ Java forces you to “handle” checked exceptions.
(a) (b)
10
Try-catch block
void p1() {
try {
//Statements that may throw exceptions
}
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
13
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
16
16
Java Library Exceptions
✦ Many Java API methods throw exceptions.
✦ 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
18
18
Creating Custom Exception Classes
19
Output:
21
– Do you want to pass more than just a string to the exception handler?
22
22