Exception (2) Java Exception Handling

时间:2022-09-24 13:36:15

The Java programming language uses exceptions to handle errors and other exceptional events.An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions.

  • Java Exception Handling Overview
  • Exception Handling Keywords
  • Exception Hierarchy
  • Useful Exception Methods
  • Creating Custom Exception Classes

Java Exception Handling Overview

Java Exception handling framework is very robust and easy to understand and use. Exception can arise from different kind of situations such as wrong data entered by user, hardware failure, network connection failure, Database server down etc.

Java being an object oriented programming language, whenever an error occurs while executing a statement, creates an exception object and then the normal flow of the program halts and JRE tries to find someone that can handle the raised exception. The exception object contains a lot of debugging information such as method hierarchy, line number where the exception occurred, type of exception etc. When the exception occurs in a method, the process of creating the exception object and handing it over to runtime environment is called “throwing the exception”.

Once runtime receives the exception object, it tries to find the handler for the exception. Exception Handler is the block of code that can process the exception object. The logic to find the exception handler is simple – starting the search in the method where error occurred, if no appropriate handler found, then move to the caller method and so on. So if methods call stack is A->B->C and exception is raised in method C, then the search for appropriate handler will move from C->B->A. If appropriate exception handler is found, exception object is passed to the handler to process it. The handler is said to be “catching the exception”. If there are no appropriate exception handler found then program terminates printing information about the exception.

Note that Java Exception handling is a framework that is used to handle runtime errors only, compile time errors are not handled by exception handling framework.

Exception Handling Keywords

Java provides specific keywords for exception handling purposes.

  • throw – We know that if any exception occurs, an exception object is getting created and then Java runtime starts processing to handle them. Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.
  • throws – When we are throwing any exception in a method and not handling it, then we need to use throws keyword in method signature to let caller program know the exceptions that might be thrown by the method. The caller method might handle these exceptions or propagate it to it’s caller method using throws keyword. We can provide multiple exceptions in the throws clause and it can be used with main() method also.
  • try-catch – We use try-catch block for exception handling in our code. try is the start of the block and catch is at the end of try block to handle the exceptions. We can have multiple catch blocks with a try and try-catch block can be nested also. catch block requires a parameter that should be of type Exception.
  • finally – finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not.

Let’s see a simple programing showing exception handling in java.

package cn.zno.exceptions;

import java.io.FileNotFoundException;
import java.io.IOException; public class Deal { public static void main(String[] args) throws FileNotFoundException,
IOException {
try {
ariseTest(-1);
ariseTest(-2);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("Releasing resources");
}
ariseTest(1);
} static void ariseTest(int code) throws FileNotFoundException, IOException {
if (code < 0) {
throw new FileNotFoundException("code: " + code);
} else {
throw new IOException("code: " + code);
}
} }

Output of above program is:

java.io.FileNotFoundException: code: -
at cn.zno.exceptions.Deal.ariseTest(Deal.java:)
at cn.zno.exceptions.Deal.main(Deal.java:)
Exception in thread "main" java.io.IOException: code:
Releasing resources
at cn.zno.exceptions.Deal.ariseTest(Deal.java:)
at cn.zno.exceptions.Deal.main(Deal.java:)

Exception Hierarchy

As stated earlier, when any exception is raised an exception object is getting created. Java Exceptions are hierarchical and inheritance is used to categorize different types of exceptions. Throwable is the parent class of Java Exceptions Hierarchy and it has two child objects – Error and Exception. Exceptions are further divided into checked exceptions and runtime exception.

  • Errors Errors are exceptional scenarios that are out of scope of application and it’s not possible to anticipate and recover from them, for example hardware failure, JVM crash or out of memory error. That’s why we have a separate hierarchy of errors and we should not try to handle these situations. Some of the common Errors are OutOfMemoryError and *Error.
  • Checked Exceptions Checked Exceptions are exceptional scenarios that we can anticipate in a program and try to recover from it, for example FileNotFoundException. We should catch this exception and provide useful message to user and log it properly for debugging purpose. Exception is the parent class of all Checked Exceptions and if we are throwing a checked exception, we must catch it in the same method or we have to propagate it to the caller using throws keyword.
  • Runtime Exception Runtime Exceptions are cause by bad programming, for example trying to retrieve an element from the Array. We should check the length of array first before trying to retrieve the element otherwise it might throw ArrayIndexOutOfBoundException at runtime. RuntimeException is the parent class of all runtime exceptions. If we are throwing any runtime exception in a method, it’s not required to specify them in the method signature throws clause. Runtime exceptions can be avoided with better programming.

Exception (2) Java Exception Handling

Useful Exception Methods

Exception and all of it’s subclasses doesn’t provide any specific methods and all of the methods are defined in the base class Throwable. The exception classes are created to specify different kind of exception scenarios so that we can easily identify the root cause and handle the exception according to it’s type. Throwable class implements Serializable interface for interoperability.

Some of the useful methods of Throwable class are:

  • public synchronized Throwable getCause() Returns the cause of this throwable.
  • public String getLocalizedMessage() Creates a localized description of this throwable. Subclasses may override this method in order to produce a locale-specific message.  For subclasses that do not override this method, the default implementation returns the same result as getMessage().
  • public String getMessage() Returns the detail message string of this throwable and the message can be provided while creating the exception through it’s constructor.
  • public void printStackTrace() Prints this throwable and its backtrace to the standard error stream.
  • public String toString() This method returns the information about Throwable in String format, the returned String contains the name of Throwable class and localized message.

Creating Custom Exception Classes

Java provides a lot of exception classes for us to use but sometimes we may need to create our own custom exception classes to notify the caller about specific type of exception with appropriate message and any custom fields we want to introduce for tracking, such as error codes. For example, let’s say we write a method to process only text files, so we can provide caller with appropriate error code when some other type of file is sent as input.

MyException.java

package cn.zno.exceptions;

public class MyException extends Exception {

    private static final long serialVersionUID = 1L;

    private ErrorCode errorCode = ErrorCode.UNKNOWN;

    public MyException(String message, ErrorCode errorCode) {
super(message);
this.errorCode = errorCode;
} public ErrorCode getErrorCode() {
return errorCode;
} public enum ErrorCode {
BAD_FILE_TYPE, FILE_NOT_FOUND_EXCEPTION, FILE_CLOSE_EXCEPTION, UNKNOWN
}
}

Deal.java

package cn.zno.exceptions;

import cn.zno.exceptions.MyException.ErrorCode;

public class Deal {

    public static void main(String[] args)  {
try {
processFile();
} catch (MyException e) {
e.printStackTrace();
System.out.println(e.getErrorCode());
System.out.println(e.getMessage());
}
} static void processFile() throws MyException {
throw new MyException("Bad File Type, notify user", ErrorCode.BAD_FILE_TYPE);
} }
cn.zno.exceptions.MyException: Bad File Type, notify user
at cn.zno.exceptions.Deal.processFile(Deal.java:)
at cn.zno.exceptions.Deal.main(Deal.java:)
BAD_FILE_TYPE
Bad File Type, notify user

Notice that we can have a separate method to process different types of error codes that we get from different methods, some of them gets consumed because we might not want to notify user for that or some of them we will throw back to notify user for the problem.

Here I am extending Exception so that whenever this exception is being produced, it has to be handled in the method or returned to the caller program, if we extends RuntimeException, there is no need to specify it in the throws clause. This is a design decision but I always like checked exceptions because I know what exceptions I can get when calling any method and take appropriate action to handle them.

Exception (2) Java Exception Handling的更多相关文章

  1. Exception &lpar;3&rpar; Java exception handling best practices

    List Never swallow the exception in catch block Declare the specific checked exceptions that your me ...

  2. Java exception handling best practices--转载

    原文地址:http://howtodoinjava.com/2013/04/04/java-exception-handling-best-practices/ This post is anothe ...

  3. Java AOP nested exception is java&period;lang&period;NoClassDefFoundError&colon; org&sol;aopalliance&sol;aop&sol;Advice &vert;&vert; Error creating bean with name &&num;39&semi;org&period;springframework&period;aop&period;aspectj&period;AspectJPointcutAdvisor&num;0&&num;39&semi; 两个异常解决办法

    贴出applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans ...

  4. nested exception is java&period;lang&period;RuntimeException&colon; Error parsing Mapper XML&period; Cause&colon; java&period;lang&period;IllegalArgumentException&colon; Result Maps collection already contains value for

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'daoSupport': ...

  5. myeclipse启动tomcat会出现 a java exception has occured错误 的解决方法

    在浏览器中可以打开tomcat,结果在myeclipse启动tomcat会出现 a java exception has occured错误 ,之后出现一个Classloader.class的文件,关 ...

  6. Spring 整合 Flex (BlazeDS)无法从as对象 到 Java对象转换的异常:org&period;springframework&period;beans&period;ConversionNotSupportedException&colon; Failed to convert property value of type 'java&period;util&period;Date' to required type 'java&period;sql&period;Timestamp' for property 'wfsj'&semi; nested exception is java&period;lang&period;Ill

    异常信息如下: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value ...

  7. jedis:exception is java&period;lang&period;VerifyError&colon; Bad type on operand stack

    项目中需要用到缓存,经过比较后,选择了redis,客户端使用jedis连接,也使用到了spring提供的spring-data-redis.配置正确后启动tomcat,发现如下异常: ======== ...

  8. Spring系列: 使用aop报错:nested exception is java&period;lang&period;NoClassDefFoundError&colon; org&sol;aspectj&sol;weaver&sol;reflect&sol;ReflectionWorld&dollar;Refle

    写了个最简单的aop例子 配置文件如下 <?xml version="1.0" encoding="UTF-8"?> <beans xmlns ...

  9. Could not load resource factory class &lbrack;Root exception is java&period;lang&period;ClassNotFoundException&colon; org&period;apache&period;tomcat&period;dbcp&period;dbcp&period;BasicDataSourceFactory&rsqb;

    WARNING: Failed to register in JMX: javax.naming.NamingException: Could not load resource factory cl ...

随机推荐

  1. Linux 查看进程和删除进程

    1. 在 LINUX 命令平台输入 1-2 个字符后按 Tab 键会自动补全后面的部分(前提是要有这个东西,例如在装了 tomcat 的前提下, 输入 tomcat 的 to 按 tab).2. ps ...

  2. json工具包比较 fastjson jackson gson

    对json进行json-object进行相互转化时,笔者接触到三种工具jar,现对其进行比较. fastjson:速度最快,阿里巴巴开源. jackson:springMvc 默认使用. gson:谷 ...

  3. css3 text-overflow属性

    页面: <ul> <li>· 测试测试测试测试测试测试</li> <li>· 测试测试测试测试测试测试</li> <li>· 测 ...

  4. AI-随机迷宫&amp&semi;迷宫求解

    本文记录了,人工智能中简单的搜索策略中的路径搜索策略中的A*算法,来实现迷宫寻路的问题.(这只是一次本人的课外作业) 完整的程序源码已经发送到我的Git.这里只记录了我的思路和感想以及收获. 产生随机 ...

  5. AngularJS中的按需加载ocLazyLoad

    欢迎大家讨论与指导 : ) 初学者,有不足的地方希望各位指出 一.前言 ocLoayLoad是AngularJS的模块按需加载器.一般在小型项目里,首次加载页面就下载好所有的资源没有什么大问题.但是当 ...

  6. activiti 中的签收与委托 操作

    原文:http://my.oschina.net/acitiviti/blog/350957 先看看activiti中关于TASK的数据库表: 其中有两个字段:OWNER_,ASSIGNEE_ 这两个 ...

  7. C&num; 注销掉事件,解决多播委托链表的问题

    c#的事件是多播委托.当绑定多个事件时,事件会依次触发,清除掉注册的委托链表:方法1  C# Code  12345678910111213141516171819202122232425262728 ...

  8. &lbrack;HNOI2015&rsqb;实验比较

    Description 小D 被邀请到实验室,做一个跟图片质量评价相关的主观实验.实验用到的图片集一共有 N 张图片,编号为 1 到 N.实验分若干轮进行,在每轮实验中,小 D会被要求观看某两张随机选 ...

  9. struts1 标签引入

    1 tld文件导入 目录结构如下 2 jsp 文件头部标签引入 <%@ page pageEncoding="gbk" contentType="text/html ...

  10. pandas DataFrame applymap&lpar;&rpar;函数

    pandas DataFrame的 applymap() 函数可以对DataFrame里的每个值进行处理,然后返回一个新的DataFrame: import pandas as pd df = pd. ...