# "throws" keyword in Java

In 
Published 2022-12-23

This tutorial explains to you how throws keyword in Java.

# "throws" keyword in Java - theory

The throws keyword in Java is used to specify the exceptions (defined by the programmer or a known Java exception) which might be raised in that method.

# "throws" keyword in Java - example

Here it is an example:

Exception1.java
public class Exception1 extends Exception {

    String message;
        
    Exception1(String message) {
       this.message = message;
    } 
          
    @Override
    public String toString() { 
        return ("Output String from toString : "+ message);
    }
}
MainApp.java
class MainApp {
     
   public static void main(String[] args) throws Exception1  {
      
       System.out.println("Before throw.");
       if (1 == 1) {
          throw new Exception1("My message");
       }
       System.out.println("After throw.");
         
   }
}

When you run this code you will get:

Before throw.
Exception in thread "main" Output String from toString : My message
at MainApp.main(MainApp.java:7)

Process finished with exit code 1