C++ 和 Java 中异常处理的比较
异常处理功能现在几乎存在于任何面向对象的语言中。在 C++ 和 Java 中,我们也可以获得这种功能。C++ 中的异常处理和 Java 中的异常处理之间存在一些相似之处,例如,在这两种语言中,我们都必须使用 try-catch 块。尽管也存在一些差异。这些差异如下所示:
在 C++ 中,我们可以抛出任何类型的作为异常的数据。任何类型的数据意味着基本数据类型和指针。在 Java 中,我们只能抛出可抛出对象。任何可抛出类的子类也可以抛出。
示例
#include <iostream>
using namespace std;
int main() {
int x = -5;
try { //protected code
if( x < 0 ) {
throw x;
}
}
catch (int x ) {
cout << "Exception Caught: thrown value is " << x << endl;
}
}输出
Exception Caught: thrown value is -5
在 C++ 中,有一个名为 catch all 的选项可以捕获任何类型的异常。语法如下:
try {
//protected code
} catch(…) {
//catch any type of exceptions
}示例
#include <iostream>
using namespace std;
int main() {
int x = -5;
char y = 'A';
try { //protected code
if( x < 0 ) {
throw x;
}
if(y == 'A') {
throw y;
}
}
catch (...) {
cout << "Exception Caught" << endl;
}
}输出
Exception Caught
在 Java 中,如果我们想捕获任何类型的异常,则必须使用 Exception 类。它是 Java 中任何异常或某些用户定义异常的超类。语法如下:
try {
//protected code
} catch(Exception e) {
//catch any type of exceptions
}C++ 没有 finally 块。但在 Java 中,有一个特殊的块称为 finally。如果我们在 finally 块中编写一些代码,它将始终被执行。如果 try 块在没有错误的情况下执行,或者发生异常,finally 块将始终被执行。
Java 在线演示
示例
public class HelloWorld {
public static void main(String []args) {
try {
int data = 25/5;
System.out.println(data);
} catch(NullPointerException e) {
System.out.println(e);
} finally {
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}输出
5 finally block is always executed rest of the code...
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP