Difference between throw and throws

 Throw is used to throw the exception inside the method.


Throws used to throw the exception in method signature.


Example:

 @GetMapping(value = "/api/dashboard/getTemplate", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)

    private ResponseEntity<byte[]> getFileTemplate(@RequestParam(value = "fileName", required = false) String fileName) throws IOException ----method signature{

try{

        File file = new File(templatePath + fileName);

        byte[] zippedData = toByteArray(new FileInputStream(file));

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.setContentDisposition(ContentDisposition.builder("attachment").filename(fileName).build());

        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        httpHeaders.setContentLength(zippedData.length);

        return ResponseEntity.ok().headers(httpHeaders).body(zippedData);

}

catch(Exception e){

throw new IOException;--- insdie the method

    }

return null;

Comments

Popular Posts