---
title: "How does JVM \"throw\" an exception?"  
description: "How does JVM \"throw\" an exception?"  
author: "Revati S Misra"  
published: 2023-07-28  
updated: 2023-07-29  
canonical: https://www.mindstick.com/forum/159352/how-does-jvm-throw-an-exception  
category: "java"  
tags: ["java", "exception", "jvm"]  
reading_time: 2 minutes  

---

# How does JVM "throw" an exception?

How does [JVM](https://www.mindstick.com/articles/12071/anatomy-of-java-virtual-machine-jvm) "throw" an [exception](https://www.mindstick.com/articles/1824/objective-c-exception-handling)?

## Replies

### Reply by Aryan Kumar

The Java Virtual Machine (JVM) throws an exception by using the `throw` keyword. The `throw` keyword is used to create an exception object and then pass it to the JVM. The JVM then searches the call stack for a matching exception handler. If a matching exception handler is found, the JVM transfers control to the exception handler. The exception handler then handles the exception, which may involve logging the exception, displaying an error message, or terminating the program.

Here is an example of how the `throw` keyword is used to throw an exception:

```plaintext
public void divide(int x, int y) throws ArithmeticException {
  if (y == 0) {
    throw new ArithmeticException("Division by zero");
  }

  int result = x / y;
  System.out.println(result);
}
```

In this example, the `divide()` method throws an `ArithmeticException` if the `y` parameter is equal to 0. The `throw` keyword is used to create an `ArithmeticException` object and then pass it to the JVM. The JVM then searches the call stack for a matching exception handler. If a matching exception handler is not found, the JVM terminates the program.

The `throw` keyword can also be used to throw checked exceptions. Checked exceptions are exceptions that must be handled or specified in the method declaration. For example, the `IOException` exception is a checked exception. If a method throws a checked exception, the method must either handle the exception or specify the exception using the `throws` keyword.

Here is an example of how the `throw` keyword is used to throw a checked exception:

```plaintext
public void readFile(String fileName) throws IOException {
  FileInputStream fis = new FileInputStream(fileName);
  int data = fis.read();
  ...
}
```

In this example, the `readFile()` method throws an `IOException` if there is an error reading the file. The `throws` keyword is used to specify that the `readFile()` method can throw an `IOException` exception.


---

Original Source: https://www.mindstick.com/forum/159352/how-does-jvm-throw-an-exception

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
