Home  >  Article  >  Java  >  Exception Handling Fundamentals

Exception Handling Fundamentals

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-16 06:08:01753browse

Fundamentos do tratamento de exceções

  • Exception handling in Java is managed by five keywords: try, catch, throw, throws and finally.

  • These keywords form an interconnected subsystem.

  • The instructions to be monitored are inside a try block.

  • If an exception occurs in the try block, it will be thrown.

  • The code can catch and handle the exception using catch.

  • System exceptions are automatically thrown by the Java runtime.

  • To throw an exception manually, use the throw keyword.

  • Exceptions that come out of a method must be declared with throws.
    The code that needs to be executed when exiting the try block must be placed in a finally block.

Using try and catch

  • The try and catch keywords are the basis of exception handling.

  • They work together: a catch block can only exist if there is a try block.

  • This is the basic format of exception handling blocks in Java.

try {
// block of code whose errors are being monitored
}
catch (TypeExceç1 obEx) {
// handler of TypeExceç1
}
catch (TypeExceç2 obEx) {
// Exceç2Type handler
}

  • The type of exception caught by the catch block determines which block will be executed.

  • We can have several catch blocks associated with a single try block.

  • Only the catch that matches the exception type will be executed, the others will be ignored.

  • If no exception is thrown, the try block will be executed normally, and catch blocks will be ignored.

  • Since JDK 7, there is try-with-resources, which automatically manages resources as I/O streams.

The above is the detailed content of Exception Handling Fundamentals. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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