# Notes
An exception handler is a section of code that gracefully responds to exceptions.
异常处理程序是一段可以优雅地响应异常的代码。
# Types of Exceptions
Checked Exceptions 已检查的异常
The exceptions which are checked by the compiler for smooth execution of program at runtime are called checked Exceptions.
由编译器检查,为了运行时能顺利执行程序。Example:
InterruptedException
,FileNotFoundException
Unchecked Exceptions 未经检查的异常
The exceptions (Runtime/Error) which are not checked by the compiler are called unchecked exceptions.
编译器未检查的异常(运行 / 错误)Example:
ArithmeticException
,NullPointerException
, etc.Fully checked Vs. Partially Checked Exceptions:
全面检查 VS. 部分检查的异常Checked Exception is said be fully checked if and only if, its entire child classes also checked, otherwise that checked exception is called partially checked exception.
仅当也检查了它的整个子类时,才说检查异常是完全检查的,否则将检查异常称为部分检查异常。
Example:
Exception | Partially checked |
IOException | Fully checked |
ArithmeticException | Unchecked Exception. |
# Handling Exceptions
To handle an potential exception, you use a try
statement.
try | |
{ | |
(try block statements...) | |
} | |
catch (ExceptionType ParameterName) | |
{ | |
(catch block statements...) | |
} |
# The finally
Clause
The try
statement may have an optional finally
clause.
If present, the finally
clause must appear after all of the catch
clauses.
如果存在,则 finally
子句必须出现在所有 catch
子句之后。
try | |
{ | |
(try block statements...) | |
} | |
catch (ExceptionType ParameterName) | |
{ | |
(catch block statements...) | |
} | |
finally | |
{ | |
(finally block statements...) | |
} |
# Creating Exception Classes
Some examples of exceptions that can affect a bank account:
可能影响银行帐户的一些例外示例:
- A negative starting balance is passed to the constructor.
传递给构造函数的负的初始余额 - A negative interest rate is passed to the constructor.
传递给构造函数的负利率 - A negative number is passed to the deposit method.
传递给存款方法的负数 - A negative number is passed to the withdraw method.
传递给提现方法的负数 - The amount passed to the withdraw method exceeds the account's balance.
传递到提现方法的金额超过了帐户的余额。
We can create exceptions that represent each of these error conditions.
我们可以创建代表每种错误情况的异常。
Hierarchy chart of Exceptions follows...
异常的层次结构图如下...
/** | |
The BankAccount class simulates a bank account. | |
*/ | |
public class BankAccount | |
{ | |
private double balance; // Account balance | |
/** | |
This constructor sets the starting balance at 0.0. | |
*/ | |
public BankAccount() | |
{ | |
balance = 0.0; | |
} | |
/** | |
This constructor sets the starting balance to the value passed as an argument. | |
@param startBalance The starting balance. | |
@exception NegativeStartingBalance When startBalance is negative. | |
*/ | |
public BankAccount(double startBalance) throws NegativeStartingBalance | |
{ | |
if (startBalance < 0) | |
throw new NegativeStartingBalance(startBalance); | |
balance = startBalance; | |
} | |
/** | |
This constructor sets the starting balance to the value in the String argument. | |
@param str The starting balance, as a String. | |
*/ | |
public BankAccount(String str) | |
{ | |
balance = Double.parseDouble(str); | |
} | |
/** | |
The deposit method makes a deposit into the account. | |
@param amount The amount to add to the | |
balance field. | |
*/ | |
public void deposit(double amount) | |
{ | |
balance += amount; | |
} | |
/** | |
The deposit method makes a deposit into the account. | |
@param str The amount to add to the | |
balance field, as a String. | |
*/ | |
public void deposit(String str) | |
{ | |
balance += Double.parseDouble(str); | |
} | |
/** | |
The withdraw method withdraws an amount from the account. | |
@param amount The amount to subtract from the balance field. | |
*/ | |
public void withdraw(double amount) | |
{ | |
balance -= amount; | |
} | |
/** | |
The withdraw method withdraws an amount from the account. | |
@param str The amount to subtract from the balance field, as a String. | |
*/ | |
public void withdraw(String str) | |
{ | |
balance -= Double.parseDouble(str); | |
} | |
/** | |
The setBalance method sets the account balance. | |
@param b The value to store in the balance field. | |
*/ | |
public void setBalance(double b) | |
{ | |
balance = b; | |
} | |
/** | |
The setBalance method sets the account balance. | |
@param str The value, as a String, to store in the balance field. | |
*/ | |
public void setBalance(String str) | |
{ | |
balance = Double.parseDouble(str); | |
} | |
/** | |
The getBalance method returns the account balance. | |
@return The value in the balance field. | |
*/ | |
public double getBalance() | |
{ | |
return balance; | |
} | |
} |
import java.io.BufferedReader; | |
import java.io.File; | |
import java.io.FileNotFoundException; | |
import java.io.FileReader; | |
import java.io.IOException; | |
class Exceptions { | |
@SuppressWarnings("resource") | |
public static void main(String s[]) { | |
FileReader reader = null; | |
try { | |
BufferedReader br; | |
br = new BufferedReader(new FileReader | |
(new File("data1.txt"))); | |
String line; | |
int i=0,ct=1; | |
while((line = br.readLine()) != null){ | |
i = Integer.parseInt(line); | |
System.out.println("Div result for record = " + ct + " -> " + (5/i) ); | |
ct++; | |
} | |
} catch (ArithmeticException e) { | |
System.out.println("Invalid operation: " + e.getMessage()); | |
} catch (FileNotFoundException e) { | |
System.out.println("File exception: " + e.getMessage()); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
//System.out.println("File exception: " + e.getMessage()); | |
} | |
finally { | |
if(reader != null){ | |
try { | |
reader.close(); | |
} catch (IOException e) { | |
//do something with the exception | |
} | |
} | |
System.out.println("--- File End ---\n"); | |
} | |
} | |
} |
/** | |
NegativeStartingBalance exceptions are thrown by the | |
BankAccount class when a negative starting balance is | |
passed to the constructor. | |
*/ | |
public class NegativeStartingBalance | |
extends Exception | |
{ | |
/** | |
This constructor uses a generic | |
error message. | |
*/ | |
public NegativeStartingBalance() | |
{ | |
super("Error: Negative starting balance"); | |
} | |
/** | |
This constructor specifies the bad starting | |
balance in the error message. | |
@param The bad starting balance. | |
*/ | |
public NegativeStartingBalance(double amount) | |
{ | |
super("Error: Negative starting balance: " + | |
amount); | |
} | |
} |
public class AccountTest | |
{ | |
public static void main(String [] args) | |
{ | |
// Force a NegativeStartingBalance exception. | |
try | |
{ | |
BankAccount account = | |
new BankAccount(-100.0); | |
} | |
catch(NegativeStartingBalance e) | |
{ | |
System.out.println(e.getMessage() ); | |
} | |
} | |
} |
import java.util.Arrays; | |
import java.util.Scanner; | |
public class AIOBSampleHandled { | |
public static void main(String args[]) { | |
int[] myArray = {897, 56, 78, 90, 12, 123, 75}; | |
System.out.println("Elements in the array are:: "); | |
System.out.println(Arrays.toString(myArray)); | |
Scanner sc = new Scanner(System.in); | |
System.out.println("Enter the index of the required element :: "); | |
try { | |
int element = sc.nextInt(); | |
System.out.println("Element in the given index is :: " + myArray[element]); | |
} catch(ArrayIndexOutOfBoundsException e) { | |
System.out.println("The index you have entered is invalid"); | |
System.out.println("Please enter an index number between 0 and 6"); | |
} | |
} | |
} |