异常处理Exception—— C++ & Java

1 篇文章 0 订阅

C++异常处理Exception

  1. throw 关键字抛出异常;try 块中放置可能抛出异常的代码,try 块中的代码被称为保护代码;catch关键字捕捉异常,并在catch块中处理。
  2. 如果在当前的try…catch…块内找不到匹配该异常对象的catch语句,则由更外层的try…catch…块来处理该异常;如果当前函数内所有的try…catch…块都不能匹配该异常,则递归回退到调用栈的上一层去处理该异常。
  3. 代码格式:
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);
        }
    }
}

运行结果如下:
在这里插入图片描述

以上内容为原创,如需引用请与作者联系。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值