C++ /python/java /C# 自定义异常处理
2017-03-27 18:03
381 查看
http://www.runoob.com/
您可以通过继承和重载 exception 类来定义新的异常。下面的实例演示了如何使用 std::exception 类来实现自己的异常:
这将产生以下结果:
Traceback (most recent call last):
File "test.py", line 11, in <module>
mye(0)
File "test.py", line 7, in mye
raise Exception("Invalid level!", level)
Exception: ('Invalid level!', 0)
// 文件名InsufficientFundsException.java
import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}<
bc8e
div class="hl-main">// 文件名称 CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
下面的 BankDemo 程序示范了如何调用 CheckingAccount 类的 deposit() 和 withdraw() 方法。//文件名称 BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}finally{ // 程序代码}
}
}
编译上面三个文件,并运行程序 BankDemo,得到结果如下所示: Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
C# 实例using System;
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
} finally{ // 要执行的语句}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:TempIsZeroException: Zero Temperature found
C++实例
finally 标准C++没有。您可以通过继承和重载 exception 类来定义新的异常。下面的实例演示了如何使用 std::exception 类来实现自己的异常:
#include <iostream> #include <exception> using namespace std; struct MyException : public exception { const char * what () const throw () { return "C++ Exception"; } }; int main() { try { throw MyException(); } catch(MyException& e) { std::cout << "MyException caught" << std::endl; std::cout << e.what() << std::endl; } catch(std::exception& e) { //其他的错误 } }
这将产生以下结果:
MyException caught C++ Exception
Python实例
#!/usr/bin/python # -*- coding: UTF-8 -*- # 定义函数 def mye( level ): if level < 1: raise Exception("Invalid level!", level) # 触发异常后,后面的代码就不会再执行 try: mye(0) // 触发异常 except "Invalid level!": print 1 else: print 2
finally:
print "xxxx"执行以上代码,输出结果为:$ python test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
mye(0)
File "test.py", line 7, in mye
raise Exception("Invalid level!", level)
Exception: ('Invalid level!', 0)
Java实例
在下面的 CheckingAccount 类中包含一个 withdraw() 方法抛出一个 InsufficientFundsException 异常。import java.io.*;
public class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
this.amount = amount;
}
public double getAmount()
{
return amount;
}
}<
bc8e
div class="hl-main">// 文件名称 CheckingAccount.java
import java.io.*;
public class CheckingAccount
{
private double balance;
private int number;
public CheckingAccount(int number)
{
this.number = number;
}
public void deposit(double amount)
{
balance += amount;
}
public void withdraw(double amount) throws
InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public double getBalance()
{
return balance;
}
public int getNumber()
{
return number;
}
}
下面的 BankDemo 程序示范了如何调用 CheckingAccount 类的 deposit() 和 withdraw() 方法。//文件名称 BankDemo.java
public class BankDemo
{
public static void main(String [] args)
{
CheckingAccount c = new CheckingAccount(101);
System.out.println("Depositing $500...");
c.deposit(500.00);
try
{
System.out.println("\nWithdrawing $100...");
c.withdraw(100.00);
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}finally{ // 程序代码}
}
}
编译上面三个文件,并运行程序 BankDemo,得到结果如下所示: Depositing $500...
Withdrawing $100...
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
namespace UserDefinedException
{
class TestTemperature
{
static void Main(string[] args)
{
Temperature temp = new Temperature();
try
{
temp.showTemp();
}
catch(TempIsZeroException e)
{
Console.WriteLine("TempIsZeroException: {0}", e.Message);
} finally{ // 要执行的语句}
Console.ReadKey();
}
}
}
public class TempIsZeroException: ApplicationException
{
public TempIsZeroException(string message): base(message)
{
}
}
public class Temperature
{
int temperature = 0;
public void showTemp()
{
if(temperature == 0)
{
throw (new TempIsZeroException("Zero Temperature found"));
}
else
{
Console.WriteLine("Temperature: {0}", temperature);
}
}
}
当上面的代码被编译和执行时,它会产生下列结果:TempIsZeroException: Zero Temperature found
相关文章推荐
- C++、Java和C#中的异常处理
- C++、Java和C#中的异常处理
- 简单了解C++、Java和C#中的异常处理
- C++、Java和C#中的异常处理
- C#自定义异常处理
- 天轰穿C# -vs2010 - 03C#的异常处理之用户自定义异常【原创】
- 黑马程序员 _Java中的异常处理及自定义异常
- C、C++、Java语言中异常处理机制浅析
- C、C++、Java语言中异常处理机制浅析
- java例程练习(自定义异常处理)
- C++、Java和C#语言在处理“虚拟私有方法”上的差异
- C++与Java异常处理的区别
- C++、Java和C#语言在处理“虚拟私有方法”上的差异
- C++与Java异常处理的区别
- JAVA异常处理 与C++的不同
- java异常处理之自定义异常类(转)
- java例程练习(自定义异常处理)
- java异常处理之自定义异常类
- C++/C#/F#/Java/JS/Lua/Python/Ruby渲染比试
- 为Notepad++配置C/C++、C#、Java、Python编译环境