search
HomeJavajavaTutorialDetailed explanation of JAVA exception class structure (with examples)

1. The general structure of the exception class

Detailed explanation of JAVA exception class structure (with examples)

2.Throwable is the super class of all exception classes.

3. It should be used when an error (exception) may occur in the program, and use the key to catch the exception for processing.

4. The catch exception structure is as follows:

public void test() {
    int num1 = 10;
    int num2 = 0;
    try {
      System.out.println(num1 / num2);  // try可能出现错误的语句块
    } catch (Exception e) {    // 异常类型 并实例化一个异常类型e,用来对出现的异常进行说明
       e.printStackTrace();       // 如果出现错误执行catch里面内容,否则跳过catch语句块
    } finally {
        System.out.println("永远都会被执行,(system.exit)特殊情况除外,");// 无论是否出现异常都会执行finally语句块
    }
}

5. Some functions directly throw exceptions when they are declared and defined. When name is called, you need to catch the exception or continue to throw exceptions.

public static void main(String[] args) {
        try {
            test();             //调用这个方法就必须捕获异常或者继续抛出异常   
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    //方法定义的时候抛出了异常
    public static void test() throws Exception {
        int num1 = 10;
        int num2 = 0;
        System.out.println(num1 / num2);             
    }

6. Custom exception class must inherit an exception parent class:

public class ExceptionTest extends Exception{
    @Override        //这个是注解,表示这是重写的方法
    public void printStackTrace() {
        System.out.println("自己定义的异常类");
        System.out.println("尝试一下如果程序没有出现异常,强制抛出这个自定义异常,可不可以捕获");
    }   
}

7. Try to use (catch) a custom exception class

public class Main {
    public static void main(String[] args) {
        try {
            test();                    //调用这个方法尝试捕获自定义异常
        } catch (ExceptionTest e) {
            e.printStackTrace();    //自定义的异常类重写了printStackTrace这个方法
        }
    }
     //继续往上抛出异常
    public static void test() throws ExceptionTest{
        throw new ExceptionTest(); //强制产生一个自定义的异常并往上抛
    }   
}

If there are any mistakes, please criticize and point them out! For more related questions, please visit the PHP Chinese website: JAVA Video Tutorial

The above is the detailed content of Detailed explanation of JAVA exception class structure (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
JVM performance vs other languagesJVM performance vs other languagesMay 14, 2025 am 12:16 AM

JVM'sperformanceiscompetitivewithotherruntimes,offeringabalanceofspeed,safety,andproductivity.1)JVMusesJITcompilationfordynamicoptimizations.2)C offersnativeperformancebutlacksJVM'ssafetyfeatures.3)Pythonisslowerbuteasiertouse.4)JavaScript'sJITisles

Java Platform Independence: Examples of useJava Platform Independence: Examples of useMay 14, 2025 am 12:14 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunonanyplatformwithaJVM.1)Codeiscompiledintobytecode,notmachine-specificcode.2)BytecodeisinterpretedbytheJVM,enablingcross-platformexecution.3)Developersshouldtestacross

JVM Architecture: A Deep Dive into the Java Virtual MachineJVM Architecture: A Deep Dive into the Java Virtual MachineMay 14, 2025 am 12:12 AM

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVM: Is JVM related to the OS?JVM: Is JVM related to the OS?May 14, 2025 am 12:11 AM

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceJava: Write Once, Run Anywhere (WORA) - A Deep Dive into Platform IndependenceMay 14, 2025 am 12:05 AM

Java implementation "write once, run everywhere" is compiled into bytecode and run on a Java virtual machine (JVM). 1) Write Java code and compile it into bytecode. 2) Bytecode runs on any platform with JVM installed. 3) Use Java native interface (JNI) to handle platform-specific functions. Despite challenges such as JVM consistency and the use of platform-specific libraries, WORA greatly improves development efficiency and deployment flexibility.

Java Platform Independence: Compatibility with different OSJava Platform Independence: Compatibility with different OSMay 13, 2025 am 12:11 AM

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),allowingcodetorunondifferentoperatingsystemswithoutmodification.TheJVMcompilesJavacodeintoplatform-independentbytecode,whichittheninterpretsandexecutesonthespecificOS,abstractingawayOS

What features make java still powerfulWhat features make java still powerfulMay 13, 2025 am 12:05 AM

Javaispowerfulduetoitsplatformindependence,object-orientednature,richstandardlibrary,performancecapabilities,andstrongsecurityfeatures.1)PlatformindependenceallowsapplicationstorunonanydevicesupportingJava.2)Object-orientedprogrammingpromotesmodulara

Top Java Features: A Comprehensive Guide for DevelopersTop Java Features: A Comprehensive Guide for DevelopersMay 13, 2025 am 12:04 AM

The top Java functions include: 1) object-oriented programming, supporting polymorphism, improving code flexibility and maintainability; 2) exception handling mechanism, improving code robustness through try-catch-finally blocks; 3) garbage collection, simplifying memory management; 4) generics, enhancing type safety; 5) ambda expressions and functional programming to make the code more concise and expressive; 6) rich standard libraries, providing optimized data structures and algorithms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools