title: Exception Handling
date: 2023-12-27
author:
- AllenYGY
status: DONE
tags:
- NOTE
- Java
- Lec6
- Program
created: 2023-12-27T01:55
updated: 2024-05-31T01:13
publish: True
Exception Handling
// Example with compile-time error 语法错误再此处不作演示
public static void division(int i, int j) { 因为无法捕捉到ArithmeticException的异常所以直接报错
int result = -1;
try {
result = i / j;
} catch (Exception e) { // Catches all exceptions!
System.out.println("Wrong: " + e.getMessage());
} catch (ArithmeticException e) { // Unreachable code.
System.out.println("Wrong: " + e.getMessage());
} finally {
System.out.println(i + " / " + j + " = " + result);
}
}
public static void main(String[] args) {
division(100, 4);
division(100, 0); // ArithmeticException: / by zero
System.out.println("End of main()");
}
//Unreachable catch block for ArithmeticException.
//It is already handled by the catch block for Exception.
(the network is temporarily down, the hard disk is full, etc.)
The Java code that you think may produce an exception is placed within a try block.
// try-catch example:
import java.util.Scanner;
public class Test2 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.print("Input an integer: ");
String s = scanner.nextLine();
try {
int i = Integer.parseInt(s);
System.out.println("i is: " + i);
}catch(NumberFormatException e) {
System.out.println("Wrong!");
}
}
}
}
try {
<code that might throw an exception>
} catch (<exception type1> <parameter1>) {
<statements handling parameter1>
} catch (<exception type2> <parameter2>) {
<statements handling parameter2>
}finally { // finally block
<statements always executed>
}
//finally example:
public class Test3 {
public static void division(int i, int j) {
int result = -1;
try {
result = i / j;
} catch(ArithmeticException e) {
System.out.println("Wrong: " + e.getMessage());
} finally {
System.out.println(i + " / " + j + " = " + result);
}
}
public static void main(String[] args) {
division(100, 4);
division(100, 0); // ArithmeticException: / by zero
System.out.println("End of main()");
}
}
A method can explicitly create an object from the Exception class (or one of its subclasses) using new and then throw the object using the throw statement. Then the method must either:
//throw
import java.util.Scanner;
public class Test6 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Input a positive integer: ");
String s = scanner.nextLine();
try {
int i = Integer.parseInt(s);
if (i <= 0) {
// This is overkill. It is easier to just print the
// error message here and then use "continue" to start
// the next iteration of the while loop.
throw new Exception(i + " <= 0 !");
}
System.out.println("i is: " + i);
} catch (Exception e) { // Catch all exceptions!
System.out.println("Catch: " + e.getMessage());
}
}
}
}
import java.util.Scanner;
public class Test7 {
public static void readPosInt() throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a positive integer: ");
String s = scanner.nextLine();
int i = Integer.parseInt(s);
if (i <= 0) {
throw new Exception(i + " <= 0 !");
}
System.out.println("i is: " + i);
}
public static void main(String[] args) {
while (true) {
try {
readPosInt(); // May throw an exception, which we need to catch.
} catch (Exception e) { // Catch all exceptions!
System.out.println("Catch: " + e.getMessage());
}
}
}
}
public Type methodName(…) throws <Exception1>,…, <ExceptionN> {
…
}
public class NotPositiveException extends Exception {
public NotPositiveException(String msg) {
// msg is the message given to the exception
when
// it is created, which will later be the
resultP
// of calling the getMessage() method.
super(msg);
}
}
import java.util.Scanner;
public class Test8 {
public static void readPosInt() throws NotPositiveException {
Scanner scanner = new Scanner(System.in);
System.out.print("Input a positive integer: ");
String s = scanner.nextLine();
int i = Integer.parseInt(s);
if (i <= 0) {
throw new NotPositiveException(i + " <= 0 !");
}
System.out.println("i is: " + i);
}
public static void main(String[] args) {
while (true) {
try {
readPosInt();
} catch (NotPositiveException e) { // If i <= 0.
System.out.println("NotPositive: " + e.getMessage());
} catch (NumberFormatException e) { // If parseInt() fails.
System.out.println("NumberFormat: " + e.getMessage());
}
}
}
}
Input a positive integer: -2
NotPositive: -2 <= 0 !
Input a positive integer: -2.5
NumberFormat: For input string: "-2.5"
class A {
void meth() throws FileNotFoundException {
}
}
class B extends A {
@Override
void meth() {
} // compiles fine
}
class C extends A {
@Override
void meth() throws IOException {
} // compile error
/*
* Exception IOException is not compatible with throws clause
* in A.meth()
*/
}
class D extends A {
@Override
void meth() throws RuntimeException {
}// compiles fine
}
interface A {
void meth() throws IOException;
}
class B implements A {
@Override
public void meth() throws FileNotFoundException {
}
// compiles fine
}
class C implements A {
@Override
public void meth() {
} // compiles fine
}
class D implements A {
@Override
public void meth() throws Exception {
} // compile error
}