Java Tutorial - Java Exception Throwing

In Java, exceptions allow us to write high-quality code, errors can be checked at compile time rather than runtime, and we can create custom exceptions that make recovery and debugging of code easier.

Java's throw keyword

Java's throw keyword is used to explicitly throw an exception.

We specify the exception object to throw. Exception object with some message describing the error. These exceptions may be related to user input, servers, etc.

We can throw checked or unchecked exception using throw keyword. It is mainly used to throw custom exceptions. We will discuss custom exceptions in this section.

We can also throw exceptions according to the conditions we define, using the throw keyword to explicitly throw exceptions. For example, if we divide one number by another, an ArithmeticException can be thrown. In this case, we just need to set the condition and throw the exception using throw keyword.

The syntax of Java's throw keyword is shown below.

throw instance, i.e.

throw new exception_class("error message");

Let's see an example of throw IOException.

throw new IOException("sorry device error");

The instance must be a Throwable type or a subclass of Throwable. For example, Exception is a subclass of Throwable, and user-defined exceptions usually extend the Exception class.

Example of Java throw keyword

Example 1: Throwing an unchecked exception

In this example, we have created a method called validate() that accepts an integer parameter. If the age is less than 18, we throw an ArithmeticException, otherwise print a welcome vote message.

In this example, we create a validate method that accepts an integer value as a parameter. If the age is less than 18, we throw an ArithmeticException, otherwise print a welcome vote message.

public class TestThrow1 {       //检查一个人是否有资格投票的函数       public static void validate(int age) {          if(age<18) {              //如果没有资格投票则抛出算术异常               throw new ArithmeticException("Person is not eligible to vote");            }          else {              System.out.println("Person is eligible to vote!!");          }      }      //主要方法       public static void main(String args[]){          //调用函数          validate(13);          System.out.println("rest of the code...");      }    }

output:

The above code throws an unchecked exception. Similarly, we can also throw unchecked and user-defined exceptions.

If a checked exception is thrown using the throw keyword, the exception must be handled using a catch block, or the method must declare it using the throws declaration.

Example 2: Throwing a checked exception

import java.io.*;    public class TestThrow2 {         //检查人是否有资格投票的功能    public static void method() throws FileNotFoundException {            FileReader file = new FileReader("C:\\Users\\Anurati\\Desktop\\abc.txt");          BufferedReader fileInput = new BufferedReader(file);                  throw new FileNotFoundException();            }      //主要方法    public static void main(String args[]){          try          {              method();          }           catch (FileNotFoundException e)           {              e.printStackTrace();          }          System.out.println("rest of the code...");      }    }

output:

Example 3: Throwing a user-defined exception

exception is everything else under the Throwable class.

// 类表示用户定义的异常  class UserDefinedException extends Exception  {      public UserDefinedException(String str)  {          // 调用父异常的构造函数            super(str);      }  }  // 在 MyException 上面使用的类    public class TestThrow3  {      public static void main(String args[])  {          try          {              // 抛出一个用户定义异常的对象              throw new UserDefinedException("This is user-defined exception");          }          catch (UserDefinedException ude)          {              System.out.println("Caught the exception");              //打印来自 MyException 对象的消息             System.out.println(ude.getMessage());          }      }  }

output:

Guess you like

Origin blog.csdn.net/2301_77463738/article/details/131464075