Home > Java > JavaBase > body text

java custom error exception

angryTom
Release: 2019-11-14 11:59:50
Original
5378 people have browsed it

java custom error exception

java custom error exception

The following code defines an exception to solve the problem of division. If the divisor appears 0 Or a negative number will report an error

Note that the custom exception code must be written in front of the application when it is run for the first time, otherwise an error will occur

无法加载主类
java.lang.NoClassDefFoundError
Copy after login

Copy the following program and run it on java

/*
 *自定义的异常类,格式如下,通过super关键字,将错误信息传递给Exception的构造函数中,之后再调用
 *toString()方法就可以打出自己想写的异常信息了
 */
class MyException extends Exception
{
    MyException(String ErrorMessage)
    {
        super(ErrorMessage);
    }
}
/*
 * 自定义异常:java自己的异常可以手动抛出也可以自动抛出,而自己定义的异常java虚拟机不认识
 * 所以,我们要通过throw关键字自己抛出异常,抛出异常之后我们有两种处理方式,第一种是抛出
 * 第二种是在下面直接try catch进行处理
 */
public class Myyichang 
{
    public static void main(String[] args) 
    {
            try
            {
                int c=chu(2,-1);
                System.out.println(c);
            }
            catch(MyException e)
            {
                System.out.println(e.toString());
            }
    }
    static int chu(int a,int b)throws MyException 
    {
        if(b<=0) 
        {
            throw new MyException("出现负数或者零了");
        }
        return a/b;
    }
}
Copy after login

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of java custom error exception. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template