Abnormal!!! Look at the examples of life's anomalies:
Under normal circumstances, from home to the company to work, only 20 minutes! But if you encounter traffic jams on the road or roads or sudden spontaneous combustion of vehicles, there is no way to go to work normally. Among them , traffic jams or roads or sudden spontaneous combustion of vehicles are abnormal.
Encounter an exception, you need to deal with, or you can only interrupt work.
What does an exception in a Java program mean?
Errors in Java fall into two categories: error (Errors) and exceptions (Exception)
errors are usually discovered and prompted by the IDE before compiling, for example, to assign an integer variable to a large value:
This is a typical error.
Program at run time problems, it is called an exception !!! If you do not consider the handling of these exceptions during programming, the program stops when an exception occurs. For example, except for the 0 error in the following example:
| 1234567 |
public staticvoidmain(String[] args) { Scanner input = newScanner(System.in); System.out.print("请输入整数:"); inti = input.nextInt(); intsum = 10/i; System.out.println(sum);} |
This code is not problematic at compile time, but entering 0 at run time will prompt for an exception:
There is a good solution to the error, in the coding link to correct the OK, but sometimes if the exception is not the developer can control (such as the above example), so developers can only pre-determine where there is the possibility of anomalies, in advance to do the processing.
| 1234567891011121314 |
publicstaticvoid main(String[] args) { Scanner input = newScanner(System.in); System.out.print("请输入整数(不能输入0):"); inti = input.nextInt(); int sum = 0; try{ sum = 10/i; } catch(Exception e) { // TODO: handle exception System.out.println("不能输入0,不能输入0,不能输入0!!!听不懂国语么!!!"); } System.out.println(sum);} |
Results:
You can find information about the exception that no longer appears in the results, and we've replaced it with our own prompt information.
Just like the following two figures, if the exception appears directly in front of the user, the user will probably no longer use your program, and if given a hint, then the user may continue to be used.
The concept of the anomaly is complete!!! , and then look at how exceptions are handled in Java.
Common exceptions in Java are:
Of course, this is only part of the list, there are a lot of anomalies are more common, when you meet the best to check the JDK.
Three ways to handle exceptions in Java:
-
Try-catch-finally
-
Throw and throws
First, try-catch-finally
The try section is required to catch an exception, and it is generally possible to put the code with the possibility of an exception.
The catch section can have 0 to many, is used to judge the exception category and processing, generally put exception handling code into it.
The finally section is optional, and the code that must be executed, whether or not an exception exists, is placed therein.
| 1234567891011121314151617 |
int firstNum = 12;intsecondNum = 0;try{ intresult = firstNum/secondNum; System.out.println("两个数字相除的结果是:"+result) }catch(ArithmeticException e) { System.out.println("算术异常:");}catch(NumberFormatException e) { System.out.println("数字转换异常");}catch(ArrayIndexOutOfBoundsException e){ System.out.println("数组下标越界异常");}catch(Exception e) { System.out.println("其他异常");}finally{ System.out.println("我是必须要执行滴,快叫爸爸!");} |
Ii. Thorw and throws
The function of this keyword is to throw an exception that it does not handle.
I asked Xiao Ming to bring me a piece of pork, Xiao Ming to the canteen found no pork (which is equivalent to the abnormal appearance), he did not know how to deal with, back to the bedroom told me no pork, and then I will deal with.
| 1234567891011121314151617181920212223 |
publicclassXiaoMing { //买食物的方法 publicvoidbuyFood(String food) throwsException{ //用一个集合表示食堂的所有菜 List<String> foods = newArrayList<String>(); foods.add("青椒鸡蛋"); foods.add("青椒肉丝"); foods.add("红烧排骨"); foods.add("土豆欢声"); //表示是否有该食物的状态 intstate = 0; //默认没有 0.没有该食物 1.有该食物 for(String string : foods) { if(food.equals(string)){ state = 1; break; } } if(state==0){ thrownewException("你要吃的菜没有了!"); } }} |
Write the test code:
A blind friend should find out what the problem is, right?
Yes, because we added throws Exception after the Buyfood () method, the IDE thought there would be an exception at the time of the call, and we had to deal with it, either by using Try-catch or by continuing to throw the exception after the Main method ( Throws Exception).
In Java, in addition to using the exceptions defined in the JDK, we can also customize the exception, this is very simple, define a class, inherit the exception class, overriding the constructor of a parameter is OK.
Well, abnormal to here is enough, need to know more friends, please Baidu it, haha!
"Software Thinking" blog address:51CTO, Blog Park , interested in small partners can go to see the relevant other blog posts.
"Java from getting started to giving up" javase introductory article: Exceptions