How to create an InvalidLineNumberException class in java with a constructor and methods | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to create an InvalidLineNumberException class in java with a constructor and methods

7th Dec 2022, 1:01 PM
Loo Student
3 Answers
+ 7
public class InvalidLineNumberException extends Exception { private int lineNumber; public InvalidLineNumberException(int lineNumber) { super("Invalid line number: " + lineNumber); this.lineNumber = lineNumber; } public int getLineNumber() { return lineNumber; } } This class extends the Exception class, which is the base class for exceptions in Java. It has a constructor that takes an int argument representing the invalid line number, and a method getLineNumber() that returns the invalid line number. The constructor uses the super keyword to call the constructor of the base Exception class, passing in a message containing the invalid line number. It then saves the line number in an instance variable so that it can be accessed later.
9th Dec 2022, 11:44 AM
Sadaam Linux
Sadaam Linux - avatar
+ 7
To use this class, you can throw an InvalidLineNumberException when you encounter an invalid line number in your code, and catch it to handle the error appropriately. For example: try { // some code that might throw InvalidLineNumberException } catch (InvalidLineNumberException ex) { System.out.println("Invalid line number: " + ex.getLineNumber()); } Note that the InvalidLineNumberException class is a checked exception, which means that any method that throws it must either catch it or declare it in the method's throws clause. This is because checked exceptions indicate a potential problem that must be handled by the caller of the method.
9th Dec 2022, 11:45 AM
Sadaam Linux
Sadaam Linux - avatar
+ 1
Check out the below link, It might help you. https://www.javatpoint.com/exception-class-in-java
8th Dec 2022, 9:23 PM
Prashant Narendra Solanki
Prashant Narendra Solanki - avatar