Exception class constructors in java

Can constructor throw exceptions in Java?

A constructor is used to initialize an object when it is created. It is syntactically similar to a method. The difference is that the constructors have same name as their class and, have no return type.

There is no need to invoke constructors explicitly these are automatically invoked at the time of instantiation.

Example

public class Example < public Example()< System.out.println("This is the constructor of the class example"); >public static void main(String args[]) < Example obj = new Example(); >>

Output

This is the constructor of the class example

Constructor throwing exceptions

Yes, just like methods you can throw exceptions from constructors in. But, if you do so, you need to catch/throw (handle) the exception at the method where you invoke the constructor. If you don’t a compile time error is generated.

Example

In the following example we have a class named Employee whose constructor throws an IOException, we are instantiating this class without handling the exception. Therefore, if you compile this program, it generates a compile time error.

import java.io.File; import java.io.FileWriter; import java.io.IOException; class Employee < private String name; private int age; File empFile; Employee(String name, int age, String empFile) throws IOException< this.name = name; this.age = age; this.empFile = new File(empFile); new FileWriter(empFile).write("Employee name is "+name+"and age is "+age); >public void display() < System.out.println("Name: "+name); System.out.println("Age: "+age); >> public class ConstructorExample < public static void main(String args[]) < String filePath = "samplefile.txt"; Employee emp = new Employee("Krishna", 25, filePath); >>

Compile time error

ConstructorExample.java:23: error: unreported exception IOException; must be caught or declared to be thrown Employee emp = new Employee("Krishna", 25, filePath); ^ 1 error

Example

To make this program work properly, wrap the instantiation line within try-catch or, throw the exception.

import java.io.File; import java.io.FileWriter; import java.io.IOException; class Employee < private String name; private int age; File empFile; Employee(String name, int age, String empFile) throws IOException< this.name = name; this.age = age; this.empFile = new File(empFile); new FileWriter(empFile).write("Employee name is "+name+"and age is "+age); >public void display() < System.out.println("Name: "+name); System.out.println("Age: "+age); >> public class ConstructorExample < public static void main(String args[]) < String filePath = "samplefile.txt"; Employee emp = null; try < emp = new Employee("Krishna", 25, filePath); >catch(IOException ex) < System.out.println("Specified file not found"); >emp.display(); > >

Output

Источник

Читайте также:  Программа периметр прямоугольника питон

Class Exception

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.

The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor’s throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Constructor Summary

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ).

Method Summary

Methods declared in class java.lang.Throwable

Methods declared in class java.lang.Object

Constructor Details

Exception

Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .

Exception

Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .

Exception

Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception’s detail message.

Exception

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause ). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException ).

Exception

protected Exception (String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

Exception class constructors in java

The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch. The class Exception and any subclasses that are not also subclasses of RuntimeException are checked exceptions. Checked exceptions need to be declared in a method or constructor’s throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

Constructor Summary

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause).

Method Summary

Methods inherited from class java.lang.Throwable

Methods inherited from class java.lang.Object

Constructor Detail

Exception

Constructs a new exception with null as its detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .

Exception

Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently be initialized by a call to Throwable.initCause(java.lang.Throwable) .

Exception

Constructs a new exception with the specified detail message and cause. Note that the detail message associated with cause is not automatically incorporated in this exception’s detail message.

Exception

Constructs a new exception with the specified cause and a detail message of (cause==null ? null : cause.toString()) (which typically contains the class and detail message of cause). This constructor is useful for exceptions that are little more than wrappers for other throwables (for example, PrivilegedActionException ).

Exception

protected Exception(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace)

Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and writable stack trace enabled or disabled.

Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.

Источник

Java – Exception Handling With Constructors in Inheritance

Java provides a mechanism to handle exceptions. To learn about exception handling, you can refer to exceptions in java. In this article, we discuss exception handling with constructors when inheritance is involved. In Java, if the constructor of the parent class throws any checked exception, then the child class constructor can throw the same exception or its parent classes. There is no problem if the parent class or child class constructor throws any unchecked exceptions. The child class constructor can throw any unchecked exception without looking for a parent class constructor.

Understanding behavior of constructor calls

Whenever a method that throws some exception is called by another method, then the calling method is responsible for handling that exception (The calling method is the method that contains the actual call; the called method is the method being called). In case of constructors, the parent class constructor is called by the child class constructor. It means the child class constructor is responsible for handling the exception thrown by the parent class constructor.

Now, for handling an exception there are two ways, one is to catch the exception and another is to throw it. But in the case of the constructor, we can’t handle it using the try-catch mechanism. The reason is that we enclose our code which can raise an exception in the try block and then catch it. The exception is raised due to a call to parent class constructor, like super(). It means if we want to handle the exception using try-catch is depicted in the below illustration.

Illustration 1

Child() < // Try- catch block try < super(); >catch (FileNotFoundException exc) < // Handling exception(code) >>

Actually, it is not correct as a call to super must be first statement in the child class constructor (refer super in java as it can be perceived from below illustration as follows:

Illustration 2

Child() < super(); // either called explicitly or added by the compiler in case of default constructor try < // your code >catch(FileNotFoundException exc) < // handling code; >>

and hence the exception can’t be caught (as its not inside the try block) and we can’t handle it using try-catch mechanism. That’s why we need to throw the exception. The below code will compile fine which will appear as follows:

// parent class constructor throws FileNotFoundException Child() throws FileNotFoundException < super(); // either called explicitly or added by the compiler in case of default constructor try < // your code >catch(FileNotFoundException exc) < // handling code; >>

Different Use-cases:

  1. Parent class constructor does not throw any checked exception
  2. Parent class constructor throws a checked exception

Now let us discuss each case in detail alongside justifying via clean java programs.

Case 1: Parent class constructor does not throw any checked exception

If the parent class constructor does not throw any exception then the child class can throw any exception or throw nothing.

Источник

Оцените статью