JAVA fundamentals of exception handling mechanism
Agenda
- Three Categories Of Exceptions
- Exceptions Hierarchy
- try-catch-finally block
- The try-with-resources
- User-defined Exceptions
- The Throws/Throw Keywords
Three Categories Of Exceptions
There have various of reasons cause different exceptions during execution or compilation, some of them are caused by user's invalid operation, others are caused by program error/bug, and others are caused by environmental/physical issue ( file resource missing,
network unavailable, e.g.). here we have three categories of exceptions. Checked exceptions, Unchecked exception and Errors.
- Checked exceptions - A checked exception is an exception occurs at the compile time, which is also called as compile time exception. The compiler will automatically prompts to programmer to handle these exceptions.
Example
import java.io.File;
import java.io.FileReader; public class FilenotFound_Demo { public static void main(String args[]) {
File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}
If you try to compile above code, you will get below exceptions.
C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error
- Uncheck exceptions - An uncheck exception is an exception occurs at the time of execution, these exceptions are also calledRuntime Exceptions. These includes programing bugs, such as logic errors or improper usage of API.
For example,ArrayIndexOutOfBoundsExceptionexception. - Errors - Error is not Exception at all, but problems that arise beyond the control of user of the program, they are invariably ignored in your code and the compiler as well, because you can rarely do anything, for example, an stack overflow
occurs, an error will arise.
Exception Hierarchy
All exceptions/errors inherit from the base class Throwable class, it contains two implortant subclass, Errors and Exception. as you see, all exception in Java are class.
- Errors- Errors indicate the pro they are serious problems that can not be handled by the program such asJVM stack overflow error, out of memory error, etc., Most of them are not caused by Java programs code, instead, caused
by the JVM, which is the programs runtime environment. Normally, programs should not try to recover Errors because it should be handled by JVM by stopping the thread. Errors also can not be traced in program as it is out of the program control. - Exceptions-Exception class has two main subclass, IOException class and RuntimeException Class. RuntimeException means validate JVM operations such as NullPointerException, ArithmeticException, ArrayIndexOutOfBoundException,etc., they
are uncheck exceptions that occurs at the time of execution. other exceptions such as IOException, SQLException are checked Exceptions.
Here is the graph to show you the Java Exception Hierarchy,
P1 Java Exception Hierarchy
the try-catch-finally block
The exception object will be created if exception occurs in try block during execution and threw out to JVM, JVM will try to look for a catch block witch is matched with the exception to handle the exception, then try-catch block ends.
The rules to match the type of exceptions: if the exception which is threw in try block, is the same class of each catch block, or the subclass of the catch block, it is considered to be matched.
that means we'd better put the underlying exceptions in more front place for high priority handling, put the business exceptions in more back place for low priority handling, otherwise the underlying exceptions may be masked by the business exceptions.
Example
public class TestException {
public static void main(String[] args) {
int a = 6;
int b = 0;
try { // try监控区域
if (b == 0) throw new ArithmeticException(); // 通过throw语句抛出异常
System.out.println("a/b的值是:" + a / b);
}
catch (ArithmeticException e) { // catch捕捉异常
System.out.println("程序出现异常,变量b不能为0。");
}
System.out.println("程序正常结束。");
}
}
ps: actually the ArithmeticException is the subclass of RuntimeException, will be threw out automatically by JVM without throw keyword explicitly in try block.
The finally block
the statement in the finally block will always be executed no matter whether exception occurs or not. if the return statement appears in try-catch block, the finally block will be executed before the return back statement and it would not be executed for
following 4 cases.
- If exceptions occur in finally block
- Have used System.exit() in preceding codes.(JVM stopping too early)
- The thread of the program has dead.
- CPU has been closed.(hardware issue)
The sequence of execution of statements in finally block
- if no exceptions are thrown by try block-statements in try block will be executed in orders one by one, the program will skip the statements in catch block and continue to execute the statements in finally block and following statements.
- if exceptions are thrown by try block but no catch block can catch the them-the exceptions will be handled by JVM, the statements in finally block will be executed but the statements following with finally will
not be executed. - if exceptions are thrown by try block and caught by catch block-the exception will be just caught by one catch block in catch block orders and other catch blocks will be skipped, in try block, the statements following with the exception
line will not be executed, after the catch block, the statements in finally block will be executed and the following codes as well.
The try-with-resources
Generally, we declare resources like streams, connections, etc. in try block then you have to explicitlyclose them in finally block. Here is a typically example when we use resources instance in try-catch-finally block.
Example
import java.io.File;
import java.io.FileReader;
import java.io.IOException; public class ReadData_Demo { public static void main(String args[]) {
FileReader fr = null;
try {
File file = new File("file.txt");
fr = new FileReader(file); char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); // prints the characters one by one
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
}catch(IOException ex) {
ex.printStackTrace();
}
}
}
}
now you can use resources without explicitly to close them in try-with-resources block, because it can be automaticallyimplicitlyclosed in final block, it is a new feature in Java 7 referred asautomatic resource management.
to use this statement, you just need to declare resource within parenthesis as below syntax, the resource will be closed at the end of the block.
Syntax
try(FileReader fr = new FileReader("file path")) {
// use the resource
}catch() {
// body of catch
}
}
Example
import java.io.FileReader;
import java.io.IOException; public class Try_withDemo { public static void main(String args[]) {
try(<strong><span style="color:#FF0000;">FileReader fr = new FileReader("E://file.txt")</span></strong>) {
char [] a = new char[50];
fr.read(a); // reads the contentto the array
for(char c : a)
System.out.print(c); // prints the characters one by one
}catch(IOException e) {
e.printStackTrace();
}
}
}
Keep in mind below points when using try-with-resources statement.
- it should implement AutoCloseable interface, the close() method will get invoked automatically at runtime.
- you can declare multiple resource in parenthesis and there will be closed in reverse order.
- the resource gets instance just before the start of try block.
User-Defined Exceptions
- All exceptions must be a child of Throwable class.
- You need to extend the Exception class if you want to create a checked exception that is enforced by the Handle or Declare rule.
- You need to extend the RuntimeException class in case you want to create a run time exception (unchecked exception)
here is a sample of user-defined exception that extends the Exception class, making it a checked exception.
Example
// File Name InsufficientFundsException.java
import java.io.*; public class InsufficientFundsException <strong><span style="color:#ff0000;">extends Exception</span></strong> {
private double amount; public InsufficientFundsException(double amount) {
this.amount = amount;
} public double getAmount() {
return amount;
}
}
Following withdraw() method in CheckingAcount class demonstrates the usage of above user-defined exception. here we will throw out an exception object that contains its own fields and method to process the parameters we pass in and the methods can be used in
higher lever class to show as format what we want, it is cool right?!
// File Name CheckingAccount.java
import java.io.*; public class CheckingAccount {
private double balance;
private int number; public CheckingAccount(int number) {
this.number = number;
} public void deposit(double amount) {
balance += amount;
} public void withdraw(double amount) <strong><span style="color:#ff0000;">throws InsufficientFundsException</span></strong> {
if(amount <= balance) {
balance -= amount;
}else {
double needs = amount - balance;
<strong><span style="color:#ff0000;">throw new InsufficientFundsException(needs);</span></strong>
}
} public double getBalance() {
return balance;
} public int getNumber() {
return number;
}
}
now we create a higher level class which is calling above CheckingAccount class and also will catch the exceptions thrown by CheckingAccount class. then we can call the user-defined exception class to process the checked exception.
// File Name BankDemo.java
public class BankDemo { public static void main(String [] args) {
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00); try {
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}<strong><span style="color:#ff0000;">catch(InsufficientFundsException e) {
System.out.println("Sorry, but you are short $" + e.getAmount());</span></strong>
e.printStackTrace();
}
}
}
Output
Depositing $500... Withdrawing $100... Withdrawing $600...
Sorry, but you are short $200.0
<strong><span style="color:#ff0000;">InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)</span></strong>
The Throws/Throw Keywords
difference
- If a method does not handle a checked exception, the method must declare it using the throws keyword, thethrows
keyword appears at the end of a method's signature. - you can throw a exception, either a newly instantiated one or an exception that you just caught, by usingthrow
keyword.
functionality
the throws is used to postpone the handling of a checked exception (to a high level class or method) and the throw is used to invoke an exception explicitly.
example
import java.io.*;
public class className { public void deposit(double amount) <span style="color:#FF0000;">throws </span>RemoteException {
// Method implementation
<span style="color:#FF0000;">throw </span>new RemoteException();
}
// Remainder of class definition
}
Reference
深入理解java异常处理机制
http://blog.csdn.net/hguisu/article/details/6155636
Java - Exceptions --- http://www.tutorialspoint.com/java/java_exceptions.htm
Lesson: Exceptions (The Java™ Tutorials > Essential Classes)
http://docs.oracle.com/javase/tutorial/essential/exceptions
JAVA fundamentals of exception handling mechanism的更多相关文章
- Java – Top 5 Exception Handling Coding Practices to Avoid
This article represents top 5 coding practices related with Java exception handling that you may wan ...
- How a C++ compiler implements exception handling
Introduction One of the revolutionary features of C++ over traditional languages is its support for ...
- Exception (2) Java Exception Handling
The Java programming language uses exceptions to handle errors and other exceptional events.An excep ...
- Exception (3) Java exception handling best practices
List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...
- Java exception handling best practices--转载
原文地址:http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/ This post is anothe ...
- [转]java-Three Rules for Effective Exception Handling
主要讲java中处理异常的三个原则: 原文链接:https://today.java.net/pub/a/today/2003/12/04/exceptions.html Exceptions in ...
- Exception Handling Considered Harmful
异常处理被认为存在缺陷 Do, or do not. There is no try. - Yoda, The Empire Strikes Back (George Lucas) by Jason ...
- HttpClient(4.3.5) - Exception Handling
HttpClient can throw two types of exceptions: java.io.IOException in case of an I/O failure such as ...
- Structured Exception Handling
https://docs.microsoft.com/en-us/windows/desktop/Debug/structured-exception-handling An exception is ...
随机推荐
- navicat内的主键和外键
数据库内的一个重点是主键另一个是外键 实体完整性{ 主键的全称:主关键字 它能够进行唯一标示某一列的 主键的三大特点是:唯一 非空 排序 一个没有主键的表不是一个完整的表,只要表设置了主键那 ...
- 一群猴子排成一圈,按1,2,...,n依次编号。然后从第1只开始数,数到第m只,把它踢出圈,从它后面再开始数,再数到第m只,在把它踢出去...,如此不停的进行下去,直到最后只剩下一只猴子为止,那只猴子就叫做大王。要求编程模拟此过程,输入m、n, 输出最后那个大王的编号
<?php/** * [猴子选大王] * @param [type] $m [猴子数] * @param [type] $n [出局次数] * @return [type] [desc ...
- drds 分库表的创建速记
关键词 :dbpartition by hash(`INVESTOR_APPLY_ID`) 格式 :dbpartition by hash(分库字段) 创建例子: CREATE TABLE `BB_J ...
- 夺命雷公狗---Thinkphp----13之前台的头尾分离和导航分离
我们在实际的开发中往往网站的头尾都是分离开来的,而且tp这点做的也很人性化,他给我们留了一个include标签可以直接引入网站的头尾部分. 我们要做的网站当然也不例外,头尾一样分离开来: 我们先用浏览 ...
- bootstrap, boosting, bagging 几种方法的联系
http://blog.csdn.net/jlei_apple/article/details/8168856 这两天在看关于boosting算法时,看到一篇不错的文章讲bootstrap, jack ...
- stdlib 头文件
stdlib 头文件即standard library标准库头文件.stdlib.h里面定义了五种类型.一些宏和通用工具函数. 类型例如size_t.wchar_t.div_t.ldiv_t和lldi ...
- ThinkPHP讲解(八)——显示、修改、添加、删除
一.显示数据 <h1>主页面</h1> <table width="100%" border="1" cellpadding=&q ...
- 【NOIP模拟赛】秦时明月
秦时明月 (sword.cpp/c/pas) [问题描述] 卫庄与盖聂又要论剑了,因为渊虹和鲨齿都是天下名剑,论剑容易互相损伤,太过可惜,于是两位换了两把木剑.因为木剑质地不匀,剑的每一段都有一个 ...
- android 设置Button或者ImageButton的背景透明 半透明 透明
Button或者ImageButton的背景设为透明或者半透明 半透明<Button android:background="#e0000000" ... /> 透明 ...
- tomcat缓存静态资源深入
之前看过apach及nginx对于静态资源(含js,图片,css等)部分的缓存,用于加速并减轻后台实际web服务器的压力. 静态资源缓存是WEB服务器优化的一种手段,基本原理如下: 1.客户端浏览器请 ...