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")  #抛出异常

 

以上是 Day 17: More Exceptions 的全部内容, 来源链接: utcz.com/a/54052.html

回到顶部