Day 17: More Exceptions

题目:

C++:

#include <stdlib.h>
#include <stdio.h>
#include <map>
#include <vector>
#include <string>
#include <math.h>
#include <algorithm>
#include <iostream>
#include <exception>
#include <stdexcept>
using namespace std;


//Write your code here
class Calculator {
public:
    int power(int n, int p) {
        if (n < 0 || p < 0) {
		throw runtime_error("n and p should be non-negative"); //抛出异常
	}
	int ans = pow(n,p);
	return ans;
    }
};

int main()
{
    Calculator myCalculator = Calculator();
    int T, n, p;
    cin >> T;
    while (T-- > 0) {
	if (scanf("%d %d", &n, &p) == 2) {
	    try {
		int ans = myCalculator.power(n, p);
		cout << ans << endl;
	    }
	    catch (exception& e) {
		cout << e.what() << endl;
	    }
	}
    }
    system("pause");
    return 0;
}

python:

#Write your code here
class Calculator():
    def power(self,n,p):
        if n<0 or p<0:
            raise RuntimeError("n and p should be non-negative")  #抛出异常
        else:
            ans=n**p
            return ans

myCalculator=Calculator()
T=int(input())
for i in range(T):
    n,p = map(int, input().split())
    try:
        ans=myCalculator.power(n,p)
        print(ans)
    except Exception as e:
        print(e)

总结:

C++:

抛出异常,throw runtime_error():

throw runtime_error("n and p should be non-negative"); //抛出异常

python:

抛出异常,raise RuntimeError():

raise RuntimeError("n and p should be non-negative")  #抛出异常

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值