C++异常处理Exception
- throw 关键字抛出异常;try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码;catch关键字捕捉异常,并在catch块中处理。
- 如果在当前的try…catch…块内找不到匹配该异常对象的catch语句,则由更外层的try…catch…块来处理该异常;如果当前函数内所有的try…catch…块都不能匹配该异常,则递归回退到调用栈的上一层去处理该异常。
- 代码格式:
try
{
// 保护代码
}catch( ExceptionName e1 )
{
// catch 块
}catch( ExceptionName e2 )
{
// catch 块
}catch( ExceptionName eN )
{
// catch 块
}
可以捕获多个异常,并进行异常处理。
- 首先看一个比较简单的异常处理案例
代码如下:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(){
char filename[80];
cout<<"请输入要读取的文件名:";
cin>>filename;
ifstream infile(filename);
try{
if(!infile){
throw string(filename);
}//throw语句抛出异常信息
} catch(string str){
cout<<"文件"<<str<<"不存在,打开失败!"<<endl;
system("pause");
return 0;
}
cout<<"读取文件"<<filename<<"内容,并在屏幕上输出:"<<endl;
for(string str;getline(infile,str);){
cout<<str<<endl;
}
system("pause");
return 0;
}
完成了以上部分的学习,相信读者们对C++的异常处理已经有了初步了解。
现在可以尝试一下完成数据结构的作业。
请尝试过以后再看下面的内容!
在我们的作业中,老师一般要求的多文件编译,例如此次作业LinkedList (链表代码)。
部分代码如下:
//LinkedList.h中部分代码
template <class T>
void LinkedList<T>::insert(int i,T x){
Node<T> *p;
p=head->next;
int count=0;
while(p!=NULL&&count<i-1){
p=p->next;
count++;
}
if(p==NULL) throw -1;//插入失败
else{
Node<T> *s;
s=new Node<T>;
s->data=x;
s->next=p->next;
p->next=s;
}
}
上述代码中,插入失败 throw -1,在main函数中代码如下:
cout<<"输入插入位置以及元素:";
cin>>i>>x;
try{
linkedList.insert(i,x);
}catch(int s){
if(s==-1)
cout<<"插入失败!"<<endl;
}
如果 throw “error” 同理。
Java异常处理Exception
- Student.java
package exceptiontest;
public class Student {
private int age;
public int getAge() {
return age;
}
//判断年龄是否合法12-30之间正常
public void setAge(int age) throws Exception {
if(age<12||age>30) {
throw new AgeInvalidException();
}
this.age = age;
}
}
- AgeInvalidException.java
package exceptiontest;
public class AgeInvalidException extends Exception {
public AgeInvalidException(){
super("年龄不合法!");
}
}
- ExceptionTest.java
package exceptiontest;
import java.util.Scanner;
public class ExceptionTest {
public static void main(String[] args) {
System.out.print("输入学生年龄:");
Student s = new Student();
Scanner scan = new Scanner(System.in);
int mytest = scan.nextInt();
try {
s.setAge(mytest);
} catch (Exception e) {
System.out.println(e);
}
}
}
运行结果如下:
以上内容为原创,如需引用请与作者联系。