Java Exception Handling

Source: Internet
Author: User
Tags class definition finally block throwable

Java Exception Handling

Exceptions are errors in the program, but not all errors are exceptions, and errors can sometimes be avoided. For example, your code is missing a semicolon, then running out of the result is the hint is error java.lang.Error; If you use System.out.println (11/0), then you are because you use 0 to do the divisor, Throws a Java.lang.ArithmeticException exception. Exceptions occur for a number of reasons, usually including the following categories:

    • The user entered illegal data.
    • The file you want to open does not exist.
    • The connection is interrupted during network communication, or the JVM memory overflows.

Some of these exceptions are caused by user errors, due to program errors, and others due to physical errors. To understand how Java exception handling works, you need to master the following three types of exceptions:

    • Check exception: The most representative of the inspection exception is the user error or the exception caused by the problem, which is not foreseen by the programmer. For example, to open a nonexistent file, an exception occurs, and these exceptions cannot be simply ignored at compile time.
    • Run-time Exceptions: Runtime Exceptions are exceptions that can be avoided by programmers. Contrary to the inspection exception, run-time exceptions can be ignored at compile time.
    • Error: The error is not an exception, but a problem that is out of the programmer's control. Errors are usually ignored in the code. For example, when a stack overflows, an error occurs, and they are not checked for compilation.

The hierarchy of the exception class. All exception classes are subclasses that inherit from the Java.lang.Exception class. The exception class is a subclass of the Throwable class. In addition to the exception class, Throwable also has a subclass error. Java programs typically do not catch errors. Errors generally occur in the event of a serious failure, which is outside the scope of the Java program processing. The error is used to indicate that a run-time environment has occurred. For example, JVM memory overflows. In general, the program does not recover from the error. The exception class has two primary subclasses: the IOException class and the RuntimeException class.

Catching exceptions

Use the try and catch keywords to catch exceptions. The Try/catch code block is placed where the exception can occur. The code in the Try/catch code block is called the Protection Code, and the syntax for using Try/catch is as follows:

try{   // 程序代码}catch(ExceptionName e1){   //Catch 块}

The Catch statement contains the declaration to catch the exception type. When an exception occurs in the protection code block, the catch block after the try is checked. If the exception that occurs is contained in a catch block, the exception is passed to the catch block, which is the same as passing a parameter to the method. In the following example, an array of two elements is declared, and an exception is thrown when the code attempts to access the third element of the array.

// 文件名 : ExcepTest.javaimport java.io.*;public class ExcepTest{   public static void main(String args[]){      try{         int a[] = new int[2];         System.out.println("Access element three :" + a[3]);      }catch(ArrayIndexOutOfBoundsException e){         System.out.println("Exception thrown  :" + e);      }      System.out.println("Out of the block");   }}以上代码编译运行输出结果如下:Exception thrown  :java.lang.ArrayIndexOutOfBoundsException: 3Out of the block

Multiple capture blocks a try block of code that follows multiple catch code blocks is called a multiple capture. The syntax for the multiple capture block is as follows:

try{    // 程序代码 }catch(异常类型1 异常的变量名1){    // 程序代码 }catch(异常类型2 异常的变量名2){    // 程序代码 }catch(异常类型2 异常的变量名2){    // 程序代码 }

The preceding code snippet contains 3 catch blocks. You can add any number of catch blocks after the try statement. If there is an exception in the protection code, the exception is thrown to the first catch block. If the data type that throws the exception matches the ExceptionType1, it is captured here. If it does not match, it is passed to the second catch block. So, until the exception is caught or through all the catch blocks.

Throws/throw Keyword: If a method does not catch an inspection exception, the method must be declared with the throws keyword. The throws keyword is placed at the tail end of the method signature. You can also throw an exception with the Throw keyword, whether it's newly instantiated or just captured. The declaration of the following method throws a RemoteException exception:

import java.io.*;public class className{   public void deposit(double amount) throws RemoteException   {      // Method implementation      throw new RemoteException();   }   //Remainder of class definition}

The Finally keyword finally keyword is used to create a block of code that executes after a try code block. The code in the finally code block is always executed, regardless of whether an exception occurs. In the finally code block, you can run an end-of-nature statement such as cleanup type.

Note the following items:

    • A catch cannot exist independently of a try.
    • Adding a finally block after Try/catch is not mandatory.
    • The try code cannot have neither a catch block nor a finally block.
    • You cannot add any code between try, catch, finally block.

Declaring custom exceptions

In Java, you can customize exceptions. Here are some things to keep in mind when writing your own exception classes.

    • All exceptions must be subclasses of Throwable.
    • If you want to write an inspection exception class, you need to inherit the exception class.
    • If you want to write a run-time exception class, you need to inherit the RuntimeException class.

You can define your own exception class as follows:

class MyException extends Exception{}

The exception class that is created only by inheriting the exception class is the check exception class.

Java Exception Handling

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.