Table of Contents
Should throw the same exception or a subtype
Example
Output
Superclass exceptions should not be thrown
Compile time error
Does not throw any exception
Home Java javaTutorial What are the rules for method coverage and exception handling in Java?

What are the rules for method coverage and exception handling in Java?

Sep 06, 2023 pm 06:29 PM
exception handling inheritance Method coverage: override method override Exception handling: exception try-catch block

What are the rules for method coverage and exception handling in Java?

When overriding a superclass method, you need to follow certain rules if the method throws an exception.

Should throw the same exception or a subtype

If a superclass method throws a certain exception, the method in the subclass should throw the same exception or its subtype.

Example

In the following example, the superclass's readFile() method throws an IOException, while the subclass's readFile() method throws a FileNotFoundException.

Since the FileNotFoundException exception is a subtype of IOException, the program can compile and execute without any errors.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
   public String readFile(String path) throws IOException {
      throw new IOException();
   }
}
public class ExceptionsExample extends Super {
   @Override
   public String readFile(String path) throws FileNotFoundException {
      Scanner sc = new Scanner(new File("E://test//sample.txt"));
      String input;
      StringBuffer sb = new StringBuffer();
      while (sc.hasNextLine()) {
         input = sc.nextLine();
         sb.append(" "+input);
      }
      return sb.toString();
   }
   public static void main(String args[]) {
      String path = "E://test//sample.txt";
      ExceptionsExample obj = new ExceptionsExample();
      try {
         System.out.println(obj.readFile(path));
      }catch(FileNotFoundException e) {
         System.out.println("Make sure the specified file exists");
      }
   }
}
Copy after login

Output

Tutorials Point is an E-learning company that set out on its journey to provide knowledge to that class of readers that responds better to online content. With Tutorials Point, you can learn at your own pace, in your own space. After a successful journey of providing the best learning content at tutorialspoint.com, we created our subscription based premium product called Tutorix to provide Simply Easy Learning in the best personalized way for K-12 students, and aspirants of competitive exams like IIT/JEE and NEET.
Copy after login

Example

Similarly, if the subclass throws the same exception as the superclass, the program will compile and execute successfully.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
   public void sampleMethod()throws FileNotFoundException {
      System.out.println("Method of superclass");
   }
}
public class ExceptionsExample extends Super {
   public void sampleMethod()throws FileNotFoundException {
      System.out.println("Method of Subclass");
   }
   public static void main(String args[]) {
      ExceptionsExample obj = new ExceptionsExample();
      obj.sampleMethod();
   }
}
Copy after login

Output

Method of Subclass
Copy after login
Copy after login

Superclass exceptions should not be thrown

If a superclass method throws an exception, the method in the subclass should not throw its superclass exception kind.

Example

In the following example, the superclass's readFile() method throws a FileNotFoundException exception, while the subclass's readFile() method throws an IOException exception, which is a superclass of FileNotFoundException. kind.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
   public String readFile(String path)throws FileNotFoundException {
      throw new FileNotFoundException();
   }
}
public class ExceptionsExample extends Super {
   @Override
   public String readFile(String path)throws IOException {
      //method body ......
   }
}
Copy after login

Compile time error

While compiling, the above program gives the following output -

ExceptionsExample.java:13: error: readFile(String) in ExceptionsExample cannot override readFile(String) in Sup
   public String readFile(String path)throws IOException {
                 ^
   overridden method does not throw IOException
1 error
Copy after login

Does not throw any exception

If the parent class method throws throw certain exceptions, you can override it without throwing any exceptions.

Example

In the following example, the sampleMethod() method of the parent class throws a FileNotFoundException exception, while the sampleMethod() method of the subclass does not throw any exception at all. Nonetheless, the program compiles and executes without any errors.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super {
   public void sampleMethod()throws FileNotFoundException {
      System.out.println("Method of superclass");
   }
}
public class ExceptionsExample extends Super {
   public void sampleMethod() {
      System.out.println("Method of Subclass");
   }
   public static void main(String args[]) {
      ExceptionsExample obj = new ExceptionsExample();
      obj.sampleMethod();
   }
}
Copy after login

Output

Method of Subclass
Copy after login
Copy after login

The above is the detailed content of What are the rules for method coverage and exception handling in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solution to solve Java assertion exception (AssertionError) Solution to solve Java assertion exception (AssertionError) Aug 25, 2023 pm 03:06 PM

Solutions to Solve Java Assertion Exceptions (AssertionError) In Java development, assertions are a commonly used debugging tool. By using assertions, we can insert some conditions into the code to ensure that the program meets the expected conditions when it is run. However, sometimes we may encounter a Java assertion exception (AssertionError), which means that the assertion condition is not met, causing the program to throw an exception. Assertion exceptions usually occur because assumptions about the code during design are incorrect or

Abstract classes in Java Abstract classes in Java Sep 22, 2023 am 11:53 AM

A class that contains the abstract keyword in its declaration is called an abstract class. An abstract class may or may not contain abstract methods, i.e. methods without a body (publicvoidget();) However, if a class has at least one abstract method, the class must be declared abstract. If a class is declared abstract, it cannot be instantiated. To use an abstract class, you must inherit it from another class and provide implementations of the abstract methods in it. If you inherit from an abstract class, you provide implementations for all abstract methods in it. Examples This section provides you with examples of abstract classes. To create an abstract class, just use the abstract keyword before the class keyword in the class declaration. /*Filename:Emplo

Exception handling in Golang Exception handling in Golang Jul 24, 2023 pm 03:20 PM

Golang has many advantages, which have been mentioned in previous articles, but there are also many shortcomings that Gopher has criticized, especially error handling. Before talking about errors and exceptions, let’s talk about two concepts: Error handling: Errors are a part of business and are foreseeable. Exception handling: not part of the business, unforeseen.

How to solve security problems encountered in Java How to solve security problems encountered in Java Jul 01, 2023 am 11:13 AM

How to solve security problems encountered in Java Introduction: With the popularity and development of the Internet, Java has become one of the most commonly used program development languages. However, due to its openness and popularity, Java programs are frequently attacked by hackers. This article will introduce some common Java security issues and explore how to solve them to protect our applications from attacks. Introduction: In Java development, security issues mainly include data leakage, authentication and authorization, exception handling, and code injection. below, i

How to solve the code hierarchical relationship problem in C++ development How to solve the code hierarchical relationship problem in C++ development Aug 22, 2023 am 11:22 AM

How to solve the code hierarchical relationship problem in C++ development. When developing complex C++ programs, a common problem is the management of code hierarchical relationships. Incorrect hierarchies can make code difficult to read, maintain, and extend. In order to solve this problem, we can adopt the following strategies. First, we can use a suitable directory structure to organize the code files. A good directory structure can arrange code files in a more orderly manner, making it easier for us to quickly locate or modify related code during the development process. Generally, it is recommended to

Solutions to common code reuse problems in C++ Solutions to common code reuse problems in C++ Oct 09, 2023 pm 01:50 PM

Solutions to common code reuse problems in C++ In C++ programming, code reuse is an important technology that can improve development efficiency and code maintainability. However, we often encounter some common code reuse problems, such as repeated code fragments, complex inheritance relationships, etc. This article will introduce several common methods to solve these problems and provide specific code examples. Function encapsulation Function encapsulation is a common code reuse method. By encapsulating a piece of code into a function, it can be called multiple times in other places to avoid writing the same code repeatedly.

How to do object-oriented programming in C++? How to do object-oriented programming in C++? Aug 27, 2023 am 08:34 AM

How to do object-oriented programming in C++? Object-Oriented Programming (OOP) is a very common and important software development paradigm. C++ is a multi-paradigm programming language that includes support for object-oriented programming. In C++, through the concepts of class and object, we can easily implement object-oriented programming. First, we need to define a class. Class is a custom

How to deal with algorithm errors in PHP? How to deal with algorithm errors in PHP? Dec 02, 2023 pm 02:30 PM

How to deal with algorithm errors in PHP? In PHP programming, handling algorithm errors is a very important task. When an error occurs in the algorithm we write, if it is not handled properly, it may cause the program to crash or produce incorrect results. Therefore, this article will introduce some common ways to deal with algorithm errors and provide specific code examples. Exception Handling In PHP, you can use the exception handling mechanism to catch and handle algorithm errors. In PHP, there are two basic exception classes: Exception and Error. we can

See all articles