Exceptions and errors:
Exceptions: Program errors in Java are mainly syntax errors and semantic errors. Errors that occur when a program is compiled and run are collectively called exceptions, which are VM (virtual machine) A way of notifying you, in which the VM lets you know that you (the developer) have made a mistake and now have an opportunity to fix it. Exception classes are used in Java to represent exceptions, and different exception classes represent different exceptions. But all exceptions in Java have a base class called Exception.
Error: It refers to a serious problem that cannot be intercepted by a reasonable application. Most are anomalies. An error is a failure of the VM (although it can be any system-level service). Therefore, errors are difficult to handle, and the average developer (not you, of course) cannot handle these errors, such as memory overflow. Like exceptions, error classes are used to represent errors in Java, and different error classes represent different errors. But all errors in Java have a base class called Error.
To sum up, we can know that the most essential difference between exceptions and errors is that exceptions can be handled by developers, while errors are native to the system and generally cannot be handled and do not require our programmers to handle them.
1. An exception is an event that occurs during the execution of a program, which interrupts the execution of normal instructions
2. Error, an action or instance that deviates from acceptable code behavior
Exceptional Structural classification:
1. Runtime exception (unchecked exception)
2. Compile time exception (checked exception)
Runtime exception is RuntimeException; the rest are all compilation exceptions
In Java Exception and error Error have a common parent class Throwable.
Error Exception
runtimeException several subclasses
1. java.lang.ArrayIndexOutOfBoundsException
Array index out-of-bounds exception. Thrown when the index into the array is negative or greater than or equal to the array size.
2, java.lang.ArithmeticException
Arithmetic condition exception. For example: integer division by zero, etc.
3.java.lang.NullPointerException
Null pointer exception. This exception is thrown when the application attempts to use null where an object is required. For example: calling the instance method of the null object, accessing the
properties of the null object, calculating the length of the null object, using the throw statement to throw null, etc.
4, java.lang.ClassNotFoundException
Class exception not found . This exception is thrown when the application attempts to construct a class based on a class name in string form and cannot find the class file with the corresponding name after traversing the CLASSPAH.
Handling of exceptions:
try{}catch{}
try{}catch{}finally{}The finally code block will be executed regardless of whether there is an exception or not
try{}finally{} is also possible It can be used in combination but catch{}finally{} cannot be used
Note: In the inheritance relationship, the subclass overrides the method of the parent class, and the scope of throwing exceptions cannot be wider than that of the parent class
Use of exceptions
This part on the use of exceptions is mainly demonstration code, which we will encounter in the process of writing code (of course only a small part), do you want to inspire others!
Example 1. This example mainly demonstrates the execution flow of the code after an exception occurs by comparing two methods.
public static void testException1() { int[] ints = new int[] { 1, 2, 3, 4 }; System.out.println("异常出现前"); try { System.out.println(ints[4]); System.out.println("我还有幸执行到吗");// 发生异常以后,后面的代码不能被执行 } catch (IndexOutOfBoundsException e) { System.out.println("数组越界错误"); } System.out.println("异常出现后"); } /*output: 异常出现前 数组越界错误 常出现后 */ 代码如下 复制代码 public static void testException2() { int[] ints = new int[] { 1, 2, 3, 4 }; System.out.println("异常出现前"); System.out.println(ints[4]); System.out.println("我还有幸执行到吗");// 发生异常以后,他后面的代码不能被执行 }First point out the shortcomings in the example. IndexOutofBoundsException is an unchecked exception, so there is no need to try...catch...to display the capture, but my purpose is to use different processing for the same exception. method and see what difference it will produce (here I can only use it for a while). When an exception occurs, the first method just jumps out of the try block, but the code behind it will still be executed. But the second kind is different and jumps directly out of the method, which is more tough. From the first method, we see that try...catch... is a "transactional" guarantee. Its purpose is to ensure that the program completes running under abnormal circumstances. At the same time, it will also inform the programmer of the program. Detailed information about the error (the details sometimes depend on the programmer's design).
Example 2. Rethrow exception
public class Rethrow { public static void readFile(String file) throws FileNotFoundException { try { BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)); } catch (FileNotFoundException e) { e.printStackTrace(); System.err.println("不知道如何处理该异常或者根本不想处理它,但是不做处理又不合适,这是重新抛出异常交给上一级处理"); //重新抛出异常 throw e; } } public static void printFile(String file) { try { readFile(file); } catch (FileNotFoundException e) { e.printStackTrace(); } } public static void main(String[] args) { printFile("D:/file"); } }The intention of exception is good, let us try to repair the program, but in reality our chance of repair is very small, we often use it to record errors information. If you are tired of constantly handling exceptions, rethrowing exceptions may be a good relief for you. Throw this exception unchanged to the upper level, to the person who calls this method, and let him think about it. From this point of view, java exceptions (of course referring to checked exceptions) have caused us a lot of trouble, although its starting point is good.
Example 3. Use of exception chain and exception loss
ExceptionA,ExceptionB,ExceptionC public class ExceptionA extends Exception { public ExceptionA(String str) { super(); } } public class ExceptionB extends ExceptionA { public ExceptionB(String str) { super(str); } } public class ExceptionC extends ExceptionA { public ExceptionC(String str) { super(str); } }Exception loss situation:
public class NeverCaught { static void f() throws ExceptionB{ throw new ExceptionB("exception b"); } static void g() throws ExceptionC { try { f(); } catch (ExceptionB e) { ExceptionC c = new ExceptionC("exception a"); throw c; } } public static void main(String[] args) { try { g(); } catch (ExceptionC e) { e.printStackTrace(); } } } /* exception.ExceptionC at exception.NeverCaught.g(NeverCaught.java:12) at exception.NeverCaught.main(NeverCaught.java:19) */Why is only ExceptionC printed but not ExceptionB? Let’s analyze this yourself!
The above situation is equivalent to missing an exception, which is very disadvantageous in our troubleshooting process. So what should we do when we encounter the above situation? This is where exception chaining comes in: saving exception information so that you can throw another exception without losing the original exception.
public class NeverCaught { static void f() throws ExceptionB{ throw new ExceptionB("exception b"); } static void g() throws ExceptionC { try { f(); } catch (ExceptionB e) { ExceptionC c = new ExceptionC("exception a"); //异常连 c.initCause(e); throw c; } } public static void main(String[] args) { try { g(); } catch (ExceptionC e) { e.printStackTrace(); } } } /* exception.ExceptionC at exception.NeverCaught.g(NeverCaught.java:12) at exception.NeverCaught.main(NeverCaught.java:21) Caused by: exception.ExceptionB at exception.NeverCaught.f(NeverCaught.java:5) at exception.NeverCaught.g(NeverCaught.java:10) ... 1 more */
这个异常链的特性是所有异常均具备的,因为这个initCause()方法是从Throwable继承的。
例4. 清理工作
清理工作对于我们来说是必不可少的,因为如果一些消耗资源的操作,比如IO,JDBC。如果我们用完以后没有及时正确的关闭,那后果会很严重,这意味着内存泄露。异常的出现要求我们必须设计一种机制不论什么情况下,资源都能及时正确的清理。这就是finally。
public void readFile(String file) { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream(file))); // do some other work } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
例子非常的简单,是一个读取文件的例子。这样的例子在JDBC操作中也非常的常见。(所以,我觉得对于资源的及时正确清理是一个程序员的基本素质之一。)
Try...finally结构也是保证资源正确关闭的一个手段。如果你不清楚代码执行过程中会发生什么异常情况会导致资源不能得到清理,那么你就用try对这段"可疑"代码进行包装,然后在finally中进行资源的清理。举一个例子:
public void readFile() { BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader( new FileInputStream("file"))); // do some other work //close reader reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
我们注意一下这个方法和上一个方法的区别,下一个人可能习惯更好一点,及早的关闭reader。但是往往事与愿违,因为在reader.close()以前异常随时可能发生,这样的代码结构不能预防任何异常的出现。因为程序会在异常出现的地方跳出,后面的代码不能执行(这在上面应经用实例证明过)。这时我们就可以用try...finally来改造:
public void readFile() { BufferedReader reader = null; try { try { reader = new BufferedReader(new InputStreamReader( new FileInputStream("file"))); // do some other work // close reader } finally { reader.close(); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
及早的关闭资源是一种良好的行为,因为时间越长你忘记关闭的可能性越大。这样在配合上try...finally就保证万无一失了(不要嫌麻烦,java就是这么中规中矩)。
再说一种情况,假如我想在构造方法中打开一个文件或者创建一个JDBC连接,因为我们要在其他的方法中使用这个资源,所以不能在构造方法中及早的将这个资源关闭。那我们是不是就没辙了呢?答案是否定的。看一下下面的例子:
public class ResourceInConstructor { BufferedReader reader = null; public ResourceInConstructor() { try { reader = new BufferedReader(new InputStreamReader(new FileInputStream(""))); } catch (FileNotFoundException e) { e.printStackTrace(); } } public void readFile() { try { while(reader.readLine()!=null) { //do some work } } catch (IOException e) { e.printStackTrace(); } } public void dispose() { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } }
这一部分讲的多了一点,但是异常确实是看起来容易用起来难的东西呀,java中还是有好多的东西需要深挖的
更多java异常与错误处理基本知识相关文章请关注PHP中文网!