Home >Java >javaTutorial >Detailed explanation and example code sharing of Java exception handling runtime exceptions

Detailed explanation and example code sharing of Java exception handling runtime exceptions

黄舟
黄舟Original
2017-05-28 09:09:472242browse

This article mainly introduces JavaException handlingRuntime exception (RuntimeException) detailed explanation and examples, friends in need can refer to it Next http://time.qq.com/?pgv_ref=aiotime

Java exception handling runtime exception (RuntimeException) detailed explanation and examples

RuntimeException

Subclass of RunntimeException:

ClassCastException

In polymorphism, you can use Instanceof to judge and avoid it

ArithmeticException

Perform if judgment, if the divisor is 0, perform return

NullPointerException

Perform if judgment to see if it is null

ArrayIndexOutOfBoundsException

Use the array length attribute to avoid crossing the boundary

These exceptions can Things that can be avoided through good programming habits of programmers

1: There is no need to handle runtime exceptions, just find the code that caused the problem and avoid it.
2: Just like a person getting angry and having a toothache, find the cause and solve it by yourself
3: This kind of exception the compiler will not check whether the programmer handles the exception
4: If it is runtime Exception, then there is no need to declare it on the function .

Case

1: Division operation function (p(int x, int y))
2: if determines if the divisor is 0, throw new ArithmeticException();
3: Function declaration throws ArithmeticException
4: main method calls p, no processing
5: Compilation passes, running normally
6: If the divisor is 0, an exception will be reported and the program will stop.
7: If it is a runtime exception, there is no need to declare it on the function.

1: The wait() method in Object class internally throws 2 exceptions IllegalMonitorStateException InterruptedException

1: Only one (throws) IllegalMonitorStateException is declared The operation is abnormal and there is no declaration.


class Demo{

 public static void main(String[] args){
  p(2, 1);
 }

 public static void p(int x, int y) {
  if (y == 0) {
   throw new ArithmeticException(); 
  }
  System.out.println(x / y);
 }
}

The above is the detailed content of Detailed explanation and example code sharing of Java exception handling runtime exceptions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn