Objects are passed as arguments in Java to send related data to a method together.It helps reduce passing many separate variables.A method can access object properties using the object reference.It makes the code cleaner and easier to manage.Objects are commonly used for real-world entities like Student, Car, or Employee.In Java, the reference of the object is passed to the method.
Throws
throws is a keyword in Java that is used in the signature of a method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.
- Declares possible exceptions.
- Mainly used with checked exceptions.
Syntax
returnType methodName() throws ExceptionName
class Test {
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Not Eligible");
} else {
System.out.println("Eligible");
}
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Top comments (0)