• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Creating custom exception in Java

King Wang

1 月 3, 2022

Java The exception system provided cannot foresee all errors that you want to report , So you can define your own exception classes to represent specific problems that you may encounter in your program .

If we want to define exception classes , Must inherit from an existing exception class , It’s better to choose an exception class with similar meaning to inherit .

The easiest way to suggest new exception types is to have the compiler generate the default constructor for you , This reduces the amount of code written :

// The default compiler builder is created , It will automatically call the default constructor of the base class
class SimpleException extends Exception{}
public class InheritingExceptions {
public void f() throws SimpleException{
System.out.println("Throw SimpleException from f()");
throw new SimpleException();
}
public static void main(String[] args) {
InheritingExceptions sed = new InheritingExceptions();
try {
sed.f();
}catch(SimpleException e) {
System.out.println("Caught it!");
}
}
}

result :

 

Define a constructor for the exception class that takes string parameters :

class MyException extends Exception{
public MyException() {}
public MyException(String msg) {
super(msg);
}
}
public class FullConstructors {
public static void f() throws MyException{
System.out.println("Throwing MyException from f()");
throw new MyException();
}
public static void g() throws MyException{
System.out.println("Throwing MyException from g()");
throw new MyException("Originated in g()");
}
public static void main(String[] args) {
try {
f();
}catch(MyException e) {
e.printStackTrace(System.out);
}try{
g();
}
catch(MyException e) {
e.printStackTrace(System.out);
}
}
}

result :

analysis : Compared with the first one , The amount of code added is not big , Two constructors define MyException How type objects are created . For the second constructor , Use super Keyword explicitly calls its base class constructor , It takes a string as a parameter .

In exception handler , Called in Throwable Class declared printStackTrace() Method . You can see from the output : It will print “ From a method call to an exception thrown ” Method call sequence for . Here the message is sent to System.out, And automatically captured and displayed in the output .

 

Thank you. !

发表回复