DEV Community

Preethi Nandhagopal
Preethi Nandhagopal

Posted on

Keywords in Exception

Keywords in Exception:
1.What is try?

  • The try block contains the code that might throw an exception.
  • Only one try is allowed, but it can be followed by multiple catch blocks and/or one finally block.
  • Without a catch or finally, try cannot exist alone.
  • A try block written inside another try block is called a nested try.
  1. What is catch?
  • The catch block is used to handle exceptions that occur inside the try block.
  • Each catch block can handle a specific type of exception (e.g., ArithmeticException, NullPointerException).
  • Multiple catch blocks allow different handling strategies for different exceptions.

try and catch in Java
In Java, exception handling is done using try, catch, finally, throw, and throws.
The most commonly used ones are try and catch, which work together to handle runtime errors (exceptions) gracefully, without stopping the program abruptly.

  1. What is finally? The finally block in Java is used with try and catch for code that must execute no matter what happens (exception occurs or not). It is mostly used for resource cleanup (closing files, database connections, releasing memory, etc.).

Key Points:

  • Always Executes->Code inside finally will run whether an exception occurs or not.
  • Works with or without catch->You can use try-finally (without catch) if you only want cleanup logic.
  • Execution Order->First, try executes → if exception occurs, catch executes → then finally executes.
  • Common Use Case->Closing resources like file streams, sockets, database connections, etc.
  • Runs Even if Exception Not Caught->Even if there is no matching catch block, finally still executes before program ends.
  1. What is throws? The throws keyword is used in a method declaration to indicate that the method may throw one or more exceptions.

Key Points:

  • Declaration, not handling->throws is used to declare exceptions, not to handle them.
  • Handling is done using try-catch.
  • Placed in Method Signature->Comes after the method parameters.
  • Example: void myMethod() throws IOException, SQLException { // code }
  • Used for Checked Exceptions->Mainly used to declare checked exceptions (like IOException, SQLException) because the compiler forces you to handle or declare them.
  • Multiple Exceptions->A method can declare multiple exceptions separated by commas.
  1. What is throw? The throw keyword is used to explicitly throw an exception from a method or block of code.

Key Points:

  • Used to Actually Throw Exception->Unlike throws (which declares), throw is used inside a method to trigger an exception.
  • Example: throw new ArithmeticException("Cannot divide by zero");
  • Must be Inside a Method/Block->Cannot be used in method declaration (that’s throws).
  • Always used inside method, constructor, or block.

Top comments (0)