网站系统设计方案/南宁seo营销推广
Java 异常
Java中的用户定义的自定义异常
Java为我们提供了创建我们自己的异常的机制,这些异常基本上是Exception的派生类。例如下面的代码中的MyException扩展了Exception类。
我们将该字符串传递给超级类的构造函数 - 在创建的对象上使用“getMessage()”函数获取的Exception。
// A Class that represents use-defined expception
class MyException extends Exception
{
public MyException(String s)
{
// Call constructor of parent Exception
super(s);
}
}
// A Class that uses above MyException
public class Main
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException("GeeksGeeks");
}
catch (MyException ex)
{
System.out.println("Caught");
// Print the message from MyException object
System.out.println(ex.getMessage());
}
}
}
输出:
Caught
GeeksGeeks
在上面的代码中,MyException的构造函数需要一个字符串作为其参数。该字符串使用super()传递给父类Exception的构造函数。Exception类的构造函数也可以在不带参数的情况下调用,并且调用super不是必需的。
// A Class that represents use-defined expception
class MyException extends Exception
{
}
// A Class that uses above MyException
public class setText
{
// Driver Program
public static void main(String args[])
{
try
{
// Throw an object of user defined exception
throw new MyException();
}
catch (MyException ex)
{
System.out.println("Caught");
System.out.println(ex.getMessage());
}
}
}
输出:
Caught
null